Beetl 快速入门

简单快速了解

Beetl 是前端视图填充数据的工具,是个页面模板,可以像 el 表达式那样操作数据,jsp 那样公共代码引用,很多好用的方法。官方模板对比:

清楚一点,beetl 很好用,但是用 beetl,最好就不要再用 jsp 什么的模板了。
BeetlSQL 操作数据库的框架,类似 Hibernate 那样直接通过对象操作数据的增删改查,简单操作,而且,像 Mybatis 那样侧重 sql,你可以在 md 文件(就是 mapper.xml)修改优化 sql 语句,而且 sql 语句的拼接判断语法,可以用 beetl 中的方法表达式,类似 js 使用很方便。官方性能对比:

官方地址:Beetl官网

快速入门开发

环境:

  • sts (spring官网的eclipse)
  • jdk8
  • maven 3.5.4

Spring5 快速接入

Beetl 接入

1.新建 maven 项目,pom.xml 文件:

    
        1.8
        1.8
        1.8
        UTF-8
        5.0.8.RELEASE
        1.2.17
        1.6.11
    

    

        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

        
        
            org.springframework
            spring-context
            ${spring.version}
        

        
            org.springframework
            spring-test
            ${spring.version}
        

        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-beans
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
            org.springframework
            spring-expression
            ${spring.version}
        

        
            org.springframework
            spring-context-support
            ${spring.version}
        

        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        

        
        
            log4j
            log4j
            ${log4j.version}
        
        

        
        
            com.ibeetl
            beetl
            2.8.5
        


    

    
        ROOT
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.1
                
                    UTF-8
                    8080
                    /
                
            
        
    

2.java 代替 web.xml的启动类 配置:

public class ApplicationInit implements WebApplicationInitializer {
 
    @Override
    public void onStartup(ServletContext servletContext) {
 
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);
        context.setServletContext(servletContext);
 
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
 
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
    }
}

3.springmvc配置文件用 java 配置:

@Configuration
@EnableWebMvc
@ComponentScan(value = "com.*")
@PropertySource(value = "classpath:config.properties")
public class AppConfig implements WebMvcConfigurer{
    
    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**")
        .addResourceLocations("/statics")
        .setCachePeriod(31556926);
    }

    /***
     * beetl配置
     */
    @Bean(name = "beetlConfig", initMethod = "init")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
        logger.info("##### GENERATE BeetlGroupUtilConfiguration BEAN #####");

        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        beetlGroupUtilConfiguration.setRoot("/WEB-INF/view");

        return beetlGroupUtilConfiguration;
    }

    /**
     * beetl视图解析器
     * 
     * @return
     */
    @Bean(name = "viewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(BeetlGroupUtilConfiguration beetlConfig) {

        logger.info("##### GENERATE BeetlSpringViewResolver BEAN #####");

        BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
        beetlSpringViewResolver.setConfig(beetlConfig);
        ;
        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
        beetlSpringViewResolver.setSuffix(".html");

        return beetlSpringViewResolver;
    }
    
}

4.测试,写一个 Controller,向 request 放入属性,解析视图:
controller

    @GetMapping("/")
    public String test(HttpServletRequest req) {
        req.setAttribute("test", "SUCCESS");
        return "index";//返回 /WEB-INF/view 下的 index.html
    }

index.html





首页


Hello

${test}

请求页面显示:

这样,spring5 已经整合了 beetl,好像没啥特别的好,没有对比就没有伤害,来个代码显示 beetl 的好用:

@for(user in users){
    ${user.name}${user.age}
@}elsefor{
    没有数据
@}


    
        ${user.name}${user.age}
    

额不知道写对了没,恩还是看个人喜好吧,@是 beet 语法的开始定界符,结束定界符是回车,默认不是这个,可以在 classpath 下的 beetl.properties 中修改:

DELIMITER_STATEMENT_START=@
DELIMITER_STATEMENT_END=

BeetlSQL 接入

1.在 pom 中添加 beetlsql 和数据源的依赖:

    
        1.8
        1.8
        1.8
        UTF-8
        5.0.8.RELEASE
        1.2.17
        1.6.11
    

    

        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

        
        
            org.springframework
            spring-context
            ${spring.version}
        

        
            org.springframework
            spring-test
            ${spring.version}
        

        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-beans
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
            org.springframework
            spring-expression
            ${spring.version}
        

        
            org.springframework
            spring-context-support
            ${spring.version}
        

        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        

        
        
            org.aspectj
            aspectjrt
            ${aspectj.version}
        

        
            org.aspectj
            aspectjweaver
            ${aspectj.version}
        

        
        
        
            mysql
            mysql-connector-java
            5.0.5
        

        
            com.alibaba
            druid
            1.0.15
        
        

        
        
            log4j
            log4j
            ${log4j.version}
        
        

        
            com.ibeetl
            beetl
            2.8.5
        


        
            com.ibeetl
            beetlsql
            2.10.30
        

    

    
        ROOT
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.1
                
                    UTF-8
                    8080
                    /
                
            
        
    
注意:beetlsql 的版本是 2.10.30,如果用之前的版本,太早的不能逆向生成 dao,有些会有不兼容的情况,如 beetlsql-2.10.29+druid-1.1.10 会产生SQLFeatureNotSupportedException 异常等。 连接

现在可以测试逆向生成 pojo 和 mapper 了:
新建一个测试类:

    public static void main(String[] args) throws Exception {
        ConnectionSource source = ConnectionSourceHelper.getSimple("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/catenate?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "root");
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/mapper 目录下
        SQLLoader loader = new ClasspathLoader("/mapper");
        // 数据库命名跟java命名一样,所以采用DefaultNameConversion,还有一个是UnderlinedNameConversion,下划线风格的,
        UnderlinedNameConversion unc = new  UnderlinedNameConversion();
        // 最后,创建一个SQLManager,DebugInterceptor 不是必须的,但可以通过它查看sql执行情况

        SQLManager sqlManager = new SQLManager(mysql,loader,source,unc, new Interceptor[]{new DebugInterceptor()});
//        sqlManager.genPojoCodeToConsole("bg_admin"); //快速生成,显示到控制台
        // 或者直接生成java文件
        //pojo代码生成配置
        GenConfig config = new GenConfig();
        //忽略表前缀bg_admin默认为BgAdmin,忽略bg为Admin
        config.setIgnorePrefix("bg");
        //dao代码生成配置,无参构造会有默认的模板
        MapperCodeGen mapper = new MapperCodeGen();
        String mapperTemplatePath = mapper.getMapperTemplate();
        //有参构造出传入的是dao生成所在的包,但是没有模板,生成后是空白
        mapper=new MapperCodeGen("com.catenate.dao");
        //把有参构造的模板位置,放入有参构造,这样可以设置dao的生成位置,又不会空白
        mapper.setMapperTemplate(mapperTemplatePath);
        //添加Dao代码生成
        config.codeGens.add(mapper);
        sqlManager.setBaseMapper(BaseMapper.class);
        //生成所有,慎用,会覆盖
        sqlManager.genALL("com.catenate.pojo", config, null);
    }

其实上面代码可以直接些模板位置,就在beetlsql依赖包下,可以写成下面这样:

MapperCodeGen mapper = new MapperCodeGen("com.catenate.dao");
mapper.setMapperTemplate(new GenConfig().getTemplate("/org/beetl/sql/ext/gen/mapper.btl"));

生成文件:

小测一下:

ConnectionSource source = ConnectionSourceHelper.getSimple("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/catenate?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "root");
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/mapper");
        // 数据库命名跟java命名一样,所以采用DefaultNameConversion,还有一个是UnderlinedNameConversion,下划线风格的,
        UnderlinedNameConversion unc = new  UnderlinedNameConversion();
        // 最后,创建一个SQLManager,DebugInterceptor 不是必须的,但可以通过它查看sql执行情况

        SQLManager sqlManager = new SQLManager(mysql,loader,source,unc, new Interceptor[]{new DebugInterceptor()});
        //使用内置sql查询用户
        int id = 1;
        Admin admin = sqlManager.unique(Admin.class,id);
        System.out.println("time==>"+admin.getCreateTime());
        AdminDao mapper = sqlManager.getMapper(AdminDao.class);
        Admin single = mapper.single(1);
        System.out.println("password==>"+single.getPassword());

beetlSql的核心就是SQLManager,包含很多方法,可以阅读官网文档

2.添加 java 配置文件,添加数据源配置,和 beetlsql 的配置:

@Configuration
@PropertySource({"classpath:config.properties"})
public class DataSourceConfig {


    @Value("${datasource.exam.url}")
    private String examUrl;
    @Value("${datasource.exam.username}")
    private String examUserName;
    @Value("${datasource.exam.password}")
    private String examPassword;

    @Value("${datasource.maxActive}")
    private int maxActive;
    @Value("${datasource.initialSize}")
    private int initialSize;
    @Value("${datasource.maxWaitMillis}")
    private long maxWaitMillis;
    @Value("${datasource.minIdle}")
    private int minIdle;
    @Value("${datasource.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;
    @Value("${datasource.minEvictableIdleTimeMillis}")
    private long minEvictableIdleTimeMillis;
    @Value("${datasource.validationQuery}")
    private String validationQuery;
    @Value("${datasource.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${datasource.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${datasource.testOnReturn}")
    private boolean testOnReturn;



    @Bean(value = "examDB")
    @Primary
    public DataSource getExamDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setName("examDB");
        druidDataSource.setUrl(examUrl);
        druidDataSource.setUsername(examUserName);
        druidDataSource.setPassword(examPassword);

        //druidDataSource配置
        druidDataSource.setMaxActive(maxActive);
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMaxWait(maxWaitMillis);
        druidDataSource.setMinIdle(minIdle);
        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        druidDataSource.setValidationQuery(validationQuery);
        druidDataSource.setTestWhileIdle(testWhileIdle);
        druidDataSource.setTestOnBorrow(testOnBorrow);
        druidDataSource.setTestOnReturn(testOnReturn);
        return druidDataSource;

    }
}
@Configuration
public class SQLManagerConfig {

    @Bean(name = "examSqlManager")
    @Primary
    public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("examDB")DataSource master){
        SqlManagerFactoryBean factoryBean=new SqlManagerFactoryBean();
        BeetlSqlDataSource source=new BeetlSqlDataSource();
        source.setMasterSource(master);
        factoryBean.setCs(source);
        factoryBean.setDbStyle(new MySqlStyle());
        //开启驼峰
        factoryBean.setNc(new UnderlinedNameConversion());
        //sql文件路径
        factoryBean.setSqlLoader(new ClasspathLoader("/mapper"));
        return factoryBean;
    }

    /**
     * 配置包扫描
     * @return
     */
    @Bean(name = "examSqlScannerConfigurer")
    public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
        BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
        conf.setBasePackage("com.catenate.dao");
        conf.setDaoSuffix("Dao");
        conf.setSqlManagerFactoryBeanName("examSqlManager");
        return conf;
    }
}

3.web测试
修改 Controller

    @Autowired
    private SQLManager sqlManager;
    
    @Autowired
    private AdminDao adminDao;
    

    @GetMapping("/")
    public String test(HttpServletRequest req) {
//        AdminDao adminDao=null;
//        try {
//            adminDao = sqlManager.getMapper(AdminDao.class);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        req.setAttribute("test", adminDao.single(1));
        return "index";
    }

可以直接注入Dao,或者注入 SQLManager,当 Dao 的方法满足不了的时候,可以用 SQLManager 来执行,SQLManager包含 Dao的所有方法

修改 index.html





首页


Hello

${test.name}

访问,页面显示

admin,就是从数据库 bg_admin中查询出来的主键为1的数据。
目录结构:

Spring Boot 快速接入

深入了解

待续。。。

你可能感兴趣的:(java)