[JavaWeb] 集成 MyBatis Generator 以及 Generator 分页插件

MyBatis Generator

MyBatis 有一个非常棒的工具叫 MyBatis Generator,是一个代码生成器。能根据数据库里面的表生成:

  • 模型类
  • Example 类(动态查询、更新和删除的类)
  • Dao 接口
  • 兼容 SQL 映射 XML 文件
  • …等等

MyBatis Generator 消除了大量的手工代码,避免了手写映射文件容易出错的问题,真心非常棒!

官网介绍地址:http://www.mybatis.org/generator/

Github下载地址:https://github.com/mybatis/generator/releases

官方自动生成的 SQL 语句

  • insert (插入)
  • update by primary key (根据主键更新记录)
  • update by example (根据条件更新记录)
  • delete by primary key (根据主键删除记录)
  • delete by example (根据条件删除记录)
  • select by primary key (根据主键查询记录)
  • select by example (根据条件查询记录集)
  • count by example (根据条件查询记录总数)

插件方式增加的 SQL 语句

  • selectByExampleByPage (根据条件查询,并根据分页参数分页)
  • insertSelective (根据条件选择性插入)
  • updateByExampleSelective (按条件更新值不为 null 的字段 )
  • updateByPrimaryKeySelective (按主键更新值不为 null 的字段 )
  • selectByExampleWithBLOGs (按条件查询,包括BLOB字段。只有当数据表中的字段类型有为二进制的才会产生。 )
  • selectByPrimaryKeyForUpdate (按主键查询并锁定)

Selective 的意思是:选择性。

1
2
3
4
比如User里面有三个字段:id,name,age,password,但是我只设置了一个字段。
User u=new user();
u.setName("张三");
insertSelective(u);

insertSelective 执行对应的sql语句的时候,只插入对应的 name 字段;(主键是自动添加的,默认插入为空)
insert into tb_user (id,name) value (null,"张三");

而 insert 则是不论你设置多少个字段,统一都要添加一遍,不论你设置几个字段,即使是一个。
insert into tb_user (id,name,age,password) value (null,"张三",null,null);

Maven 引入 MyBatis Generator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>cn.doity</groupId>
<artifactId>mybatis-generator-bySweb</artifactId>
<version>1.0.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/test/resources/mybatis-generator-bySweb.jar</systemPath>
</dependency>
<!--通过 Maven 引入-->
<!--<dependency>-->
<!--<groupId>cn.doity</groupId>-->
<!--<artifactId>mybatis-generator-bySweb</artifactId>-->
<!--<version>1.0.1</version>-->
<!--</dependency>-->
</dependencies>
</plugin>

从上面配置可以看到,generator 引入 mysql 驱动以及一个插件 mybatis-generator-bySweb.jar,这是上述“插件方式增加的 SQL 语句”的插件,将自定义的 SQL 语句的类打包成 jar 包后再引入。

generator 配置

从配置上上可以看到,generator 配置放在 /src/main/resources/generator/generatorConfig.xml
具体的配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >

<generatorConfiguration>

<!--修改config.properties中的模块名称、表名即可-->

<properties resource="conn.properties"/>

<context id="mysqlTables" targetRuntime="MyBatis3">

<!--<property name="daoPackage" value="cn.doity.${moduleName}.persistence.custom"/>-->
<property name="daoPackage" value="cn.doity.dao"/>

<!--序列化-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

<!--插入成功后返回ID-->
<plugin type="cn.doity.common.generator.plugin.InsertAndReturnKeyPlugin"/>

<!--分页查询功能-->
<plugin type="cn.doity.common.generator.plugin.SelectByPagePlugin"/>

<!--生成带有for update后缀的select语句插件-->
<plugin type="cn.doity.common.generator.plugin.SelectForUpdatePlugin"/>

<commentGenerator>
<!-- 代码合并时需要用到 -->
<property name="suppressAllComments" value="false"/>
<!--关闭注释-->
<property name="suppressDate" value="true"/>
</commentGenerator>

<!-- 数据库连接方式 -->
<jdbcConnection driverClass="${jdbc.dr}" connectionURL="${jdbc.uip}"
userId="${jdbc.un}" password="${jdbc.pw}">

</jdbcConnection>

<javaTypeResolver type="cn.doity.common.generator.plugin.MyTypeResolver">
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>

<!--生成的model 包路径 -->
<javaModelGenerator targetPackage="${model.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>

<!--生成xml mapper文件 路径 -->
<sqlMapGenerator targetPackage="${xml.mapper.package}" targetProject="${target.resources}">
<property name="enableSubPackages" value="ture"/>
</sqlMapGenerator>

<!-- 生成的Dao接口 的包路径 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
</javaClientGenerator>

<!--表别名在mysql下面,删除语句会有问题,alias="t"-->
<table tableName="${tableName}" alias="t">
</table>
</context>
</generatorConfiguration>

conn.properties 连接信息的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## 数据库信息
jdbc.dr=com.mysql.jdbc.Driver
jdbc.uip=jdbc:mysql://127.0.0.1:3306/superweb?useUnicode=true&characterEncoding=UTF8
jdbc.un=root
jdbc.pw=

### Generator 相关设置
## 表名
tableName=%
## 模块名
moduleName=abc
# 包路径配置
model.package=cn.doity.entity
dao.package=cn.doity.dao
xml.mapper.package=mapper
target.resources=src/main/resources
target.project=src/main/java

按条件查询并分页示例

Country 类是代表国家实体,里面 countryName 代表国家名字,示例是通过国家名字模糊查询。

Page 类封装了分页相关参数,TotalCount 表示总记录数,PageNo 页码,PageSize 页面大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<Country> selectByModelAndPage(Country country, Page page) {
CountryExample countryExample = new CountryExample();
CountryExample.Criteria criteria = countryExample.createCriteria();

if (StringUtils.isNotBlank(country.getCountryname())) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('%').append(country.getCountryname()).append('%');
criteria.andCountrynameLike(stringBuilder.toString());
}
int count = countryMapper.countByExample(countryExample);
page.setTotalCount(count);

countryExample.setOrderByClause("字段名 ASC"); //升序排列,desc为降序排列。
countryExample.setDistinct(false)//去除重复,boolean型,true为选择不重复的记录。
countryExample.setPageClause(page.getPageNo()+ "," + page.getPageSize());
countryExample.setOrderByClause("id asc");
List<Country> countryList = countryMapper.selectByExampleByPage(countryExample);
return countryList;
}

MyBatis 相关工具推荐

abel533 作者有两个 MyBatis 相关工具:通用 Mapper 与 分页插件PageHelper。都挺好用,欢迎大家去使用一下。

Github 地址:https://github.com/abel533

参考资料