SpringBoot配置Mybatis通用Mapper和Pagehelper

前些日子在做微信点餐项目中学习使用了JPA,不用像Mybatis一样写一堆Mapper和XML,继承接口的方式确实很方便,但是遇上多表查询就很头疼了。
直到我发现了一位大牛写的Mybatis通用Mapper,通用Mapper可以简化对单表的CRUD操作,PageHelper分页插件可以自动拼接分页SQL,并且可以使用MyBatis Geneator来自动生成实体类,Mapper接口和Mapper xml代码。
最重要的是,MapperXML文件中一下子变得简洁多了,复杂的查询自己手动添加即可,非常的方便。

1.前言

插件地址及作者链接https://gitee.com/free

参考

github-pagehelper分页插件
github-通用Mapper
Oracle数据库-MyBatis通用Mapper和PageHelper

2.准备

环境

  • 基础框架:Spring Boot
  • Java版本: 1.8
  • 数据库:MySQL5.6

POM文件

pom文件中引入:

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
<!-- Mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
```
接着在plugins中添加MyBatis Geneator插件:
```xml
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<!-- 数据库连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 配置文件路径,见3.4 -->
<configurationFile>src/main/resources/config/mybatis-generator.xml</configurationFile>
</configuration>
</plugin>

数据库准备

1
2
3
4
5
6
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`countryname` varchar(255) DEFAULT NULL COMMENT '名称',
`countrycode` varchar(255) DEFAULT NULL COMMENT '代码',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=10011 DEFAULT CHARSET=utf8 COMMENT='国家信息';

3.配置

配置Mybatis

在Spring Boot配置文件application.yml中配置MyBatis:

1
2
3
4
5
6
7
mybatis:
# type-aliases扫描路径
type-aliases-package: top.d3rc.common.domain
# mapper xml实现扫描路径
mapper-locations: classpath:mapper/*.xml
property:
order: BEFORE

配置通用Mapper

先自定义一个通用Mapper接口

注意!!该接口不能被扫描到,应该和其他Mapper分开。其他的Mapper都需要继承这个接口。

这里我放在了common.config包下。

1
2
3
4
5
package top.d3rc.common.config;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

将刚才的通用接口

在Spring Boot配置文件application.yml中配置通用Mapper:

1
2
3
4
5
6
mapper:
#mappers 多个接口时逗号隔开
mappers: top.d3rc.common.config.MyMapper
not-empty: false
identity: MYSQL
order: after

配置Pagehelper

一般情况下,你不需要做任何配置。

如果需要配置,可以看官方文档

配置MBG的配置文件

在路径src/main/resources/config下新建mybatis-generator.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
<?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>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<!-- 十分重要!填写自定义的通用Mapper的引用 -->
<property name="mappers" value="top.d3rc.common.config.MyMapper"/>
<!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
<property name="caseSensitive" value="false"/>
</plugin>
<!-- 阻止生成自动注释 -->
<commentGenerator>
<property name="javaFileEncoding" value="UTF-8"/>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/yours"
userId="yours"
password="yours">
</jdbcConnection>
<!-- 实体类生成目录 -->
<javaModelGenerator targetPackage="top.d3rc.common.domain" targetProject="src/main/java"/>
<!-- 映射文件生成目录 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- Dao类生成目录 -->
<javaClientGenerator targetPackage="top.d3rc.common.dao" targetProject="src/main/java" type="XMLMAPPER" />
<!-- 需要自动生成的表,演示中只有这一个 -->
<table tableName="country" >
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>

配置包扫描

要让Spring Boot扫描到Mapper接口,需要在Spring Boot入口类中加入@MapperScan(“com.springboot.mapper”)注解。

1
2
3
4
5
6
7
8
9
10
//这里一定要是tk开头的,不能是org开头的
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
//配置dao类所在的包,可以使用通配符
@MapperScan("top.d3rc.common.dao")
public class TkDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TkDemoApplication.class, args);
}
}

配置数据库

在Spring Boot配置文件application.yml中配置数据库连接:

1
2
3
4
5
6
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/yours
username: yours
password: yours

4.启动MBG自动生成

配置好上述文件后,在控制台运行命令mybatis-generator:generate,或者在IDEA插件中双击运行:

生成的实体类

1
2
3
4
5
6
7
8
9
10
public class Country {
/** 主键 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String countryname;
private String countrycode;
}

生成的Mapper类

干净整洁,复杂业务可以自由扩展

1
2
3
4
5
import top.d3rc.common.config.MyMapper;
import top.d3rc.common.domain.Country;
public interface CountryMapper extends MyMapper<Country> {
}

生成的映射文件

干净整洁,复杂SQL可以自由扩展

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.d3rc.common.dao.CountryMapper">
<resultMap id="BaseResultMap" type="top.d3rc.common.domain.Country">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="countryname" jdbcType="VARCHAR" property="countryname" />
<result column="countrycode" jdbcType="VARCHAR" property="countrycode" />
</resultMap>
</mapper>

5.通用Service

我们可以定义一个通用的Service,在其中定义一些通用的方法,便于其他Service继承实现:

通用Service接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public interface IService<T> {
List<T> selectAll();
T selectByKey(Object key);
int save(T entity);
int delete(Object key);
int updateAll(T entity);
int updateNotNull(T entity);
List<T> selectByExample(Object example);
}

通用Service实现类

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
public abstract class BaseService<T> implements IService<T> {
@Autowired
protected Mapper<T> mapper;
public Mapper<T> getMapper() {
return mapper;
}
@Override
public Long getSequence(@Param("seqName") String seqName){
return seqenceMapper.getSequence(seqName);
}
@Override
public List<T> selectAll() {
//说明:查询所有数据
return mapper.selectAll();
}
@Override
public T selectByKey(Object key) {
//说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
return mapper.selectByPrimaryKey(key);
}
@Override
public int save(T entity) {
//说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
return mapper.insert(entity);
}
@Override
public int delete(Object key) {
//说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
return mapper.deleteByPrimaryKey(key);
}
@Override
public int updateAll(T entity) {
//说明:根据主键更新实体全部字段,null值会被更新
return mapper.updateByPrimaryKey(entity);
}
@Override
public int updateNotNull(T entity) {
//根据主键更新属性不为null的值
return mapper.updateByPrimaryKeySelective(entity);
}
@Override
public List<T> selectByExample(Object example) {
//说明:根据Example条件进行查询
//重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列
return mapper.selectByExample(example);
}
}

自定义CountryService继承通用Service接口

1
2
public interface CountryService extends IService<Country> {
}

CountryService的实现类

1
2
3
@Service
public class CountryServiceImpl extends BaseService<Country> implements CountryService {
}

这样即可在UserService中使用BaseService中的通用方法了。

6.测试

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
64
65
@SpringBootTest
@RunWith(SpringRunner.class)
public class CountryServiceImplTest {
@Autowired
CountryService service;
/*测试新增*/
@Test
public void save(){
Country country = new Country();
country.setCountryname("England");
country.setCountrycode("777");
int i = service.save(country);
System.out.println(i);
}
/*测试删除*/
@Test
public void delete(){
Example example = new Example(Country.class);
example.createCriteria().andCondition("countryname = 'England'");
List<Country> list = service.selectByExample(example);
int i = service.delete(list.get(0));
System.out.println(i);
}
/*测试更新*/
@Test
public void update(){
Country country = service.selectByKey(1);
country.setCountryname("updatedUSA");
int i = service.updateNotNull(country);
System.out.println(i);
}
/*测试通过id查询*/
@Test
public void findById(){
Country country = service.selectByKey(1);
System.out.println(country.getCountryname());
}
/*测试查询全部*/
@Test
public void findAll(){
List<Country> list = service.selectAll();
for (Country country : list) {
System.out.println(country.getCountryname());
}
}
/*测试分页*/
@Test
public void page(){
PageHelper.startPage(2, 2);
List<Country> list = service.selectAll();
PageInfo<Country> pageInfo = new PageInfo<>(list);
List<Country> result = pageInfo.getList();
for (Country country : result) {
System.out.println(country.getCountryname());
}
}
}