介绍

jdbc 配合 Enjoy sql解析器真心不错,弥补了jpa不支持复杂的sql查询缺陷
  1. Enjoy
  2. jdbc

1、pom包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jfinal</groupId>
            <artifactId>enjoy</artifactId>
            <version>4.8</version>
        </dependency>

3、jfinal配置

@Configuration
public class SpringBootConfig {

    @Bean(name = "jfinalViewResolver")
    public JFinalViewResolver getJFinalViewResolver() {
        // 创建用于整合 spring boot 的 ViewResolver 扩展对象
        JFinalViewResolver jfr = new JFinalViewResolver();
        // 获取 engine 对象,对 enjoy 模板引擎进行配置,配置方式与前面章节完全一样
        Engine engine = JFinalViewResolver.engine;
        // 上面的代码获取到了用于 sql 管理功能的 Engine 对象,接着就可以开始配置了
        engine.addSharedMethod(new StrKit());
        // 热加载配置能对后续配置产生影响,需要放在最前面
        engine.setDevMode(true);
        // 使用 ClassPathSourceFactory 从 class path 与 jar 包中加载模板文件
        engine.setToClassPathSourceFactory();
        return jfr;
    }
}

3、使用

   @Service
public class SchoolServiceImpl implements SchoolService {

    private final JFinalViewResolver jFinalViewResolver;
    private final JdbcTemplate jdbcTemplate;

    public SchoolServiceImpl(JdbcTemplate jdbcTemplate, JFinalViewResolver jFinalViewResolver) {
        this.jdbcTemplate = jdbcTemplate;
        this.jFinalViewResolver = jFinalViewResolver;
    }

    @Override
    public Object getCounts() {
        String sql = "SELECT * from school WHERE grade_name = '一年级'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list1 = StringUtils.formatHumpNameForList(list);
        System.out.println("list1 = " + list1);
//        HashMap<String, Object> data = new HashMap<>(10);
//        data.put("gradeName", "一年级");
        SchoolDto schoolDto = new SchoolDto();
//        schoolDto.setGradeName("一年级");
        Map<String, Object> data = MapObjUtil.object2Map(schoolDto);
        String path = FileUtils.getSql("school");
        String str = jFinalViewResolver.getEngine().getTemplateByString(path).renderToString(data);
        System.out.println("str = " + str);
        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(str);
        List<Map<String, Object>> list3 = StringUtils.formatHumpNameForList(list2);
        System.out.println("list3 = " + list3);
        String string = JSON.toJSONString(list3);
        System.out.println("string = " + string);
        List<School> schools = JSON.parseArray(string,School.class);
        System.out.println("schools = " + schools);
        List<School> schoolList = TreeUtils.treeMenuCountsList(schools,0);
        System.out.println("schoolList = " + schoolList);
        return list1;
    }
}

源码

Last modification:March 23rd, 2020 at 10:52 pm
如果觉得我的文章对你有用,请随意赞赏