简单快速了解
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 文件:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.8.RELEASE</spring.version>
<log4j.version>1.2.17</log4j.version>
<aspectj.version>1.6.11</aspectj.version>
</properties>
<dependencies>
<!-- Java Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- spring 相关start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring 相关end -->
<!-- 日志 start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 日志 end -->
<!-- beetl模板 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
<build>
<finalName>ROOT</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<encoding>UTF-8</encoding>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h2>Hello</h2>${test}
</body>
</html>
请求页面显示:
这样,spring5 已经整合了 beetl,好像没啥特别的好,没有对比就没有伤害,来个代码显示 beetl 的好用:
@for(user in users){
<tr><td>${user.name}</td><td>${user.age}</td></tr>
@}elsefor{
<tr><td colspan="2">没有数据</td></tr>
@}
用 <c:forEach>
<c:if test="${!empty users}">
<c:forEach items="${users}" var="user">
<tr><td>${user.name}</td><td>${user.age}</td></tr>
</c:forEach>
</c:if>
额不知道写对了没,恩还是看个人喜好吧,@是 beet 语法的开始定界符,结束定界符是回车,默认不是这个,可以在 classpath 下的 beetl.properties 中修改:
DELIMITER_STATEMENT_START=@
DELIMITER_STATEMENT_END=
BeetlSQL 接入
1.在 pom 中添加 beetlsql 和数据源的依赖:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.8.RELEASE</spring.version>
<log4j.version>1.2.17</log4j.version>
<aspectj.version>1.6.11</aspectj.version>
</properties>
<dependencies>
<!-- Java Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- spring 相关start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring 相关end -->
<!-- AOP start -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- AOP end -->
<!-- 数据源 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.15</version>
</dependency>
<!-- 数据源 end -->
<!-- 日志 start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 日志 end -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetlsql</artifactId>
<version>2.10.30</version>
</dependency>
</dependencies>
<build>
<finalName>ROOT</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<encoding>UTF-8</encoding>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
注意: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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h2>Hello</h2>${test.name}
</body>
</html>
访问,页面显示
admin,就是从数据库 bg_admin中查询出来的主键为1的数据。
目录结构:
Spring Boot 快速接入
深入了解
待续。。。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。