1. 通用Mapper简介
1.1. 项目地址
MyBatis分页插件和通用Mapper都托管在码云和Github,作者是同一个人。
作者是这样介绍的:
- 通用Mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。
- 极其方便的使用MyBatis单表的增删改查。
- 支持单表操作,不支持通用的多表联合查询
1.2. 为什么要使用通用Mapper
有了MBG,已经极大地简化了MyBatis开发。MBG生成的方法都是单表查询,通过Mapper也是单表查询,为什么还要使用通用Mapper呢?
MBG只是帮我们快速生成Mapper接口和xml。当实体类发生修改,你还要重新运行逆向工程,覆盖原来的Mapper接口和xml,十分麻烦。
使用通用Mapper,可以动态生成SQL,也就可以省略xml。实体类发生修改,生成的SQL跟着就修改了,不需要人为地做其它修改,给开发带来很多便利的好处。
通用Mapper还支持批量操作,而MBG不支持
1.3. 对实体类的要求
考虑到基本数据类型在Java 类中都有默认值,会导致MyBatis 在执行相关操作时很难判断当前字段是否为null,所以在MyBatis 环境下使用Java 实体类时尽量不要使用基本数据类型,都使用对应的包装类型
2. Spring整合通用Mapper
参考:
- Github官方项目wiki: 与Spring集成 https://github.com/abel533/Mapper/wiki/1.2-spring
2.1. 依赖
正常情况下,Spring 和 MyBatis 的集成环境中,应该已经存在下面的依赖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<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>版本号</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>版本号</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>版本号</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>版本号</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>版本号</version>
</dependency>
集成通用 Mapper 在上面的基础上添加下面的依赖:1
2
3
4
5<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>最新版本</version>
</dependency>
2.2. 实体类
1 |
|
2.3. Mapper接口
相较于原生MyBatis,通用Mapper省略了xml,也没有使用注解开发,就能实现增删查改。这不是平白无故就能省略的,这要求Mapper接口继承Mapper<T>,泛型参数就是实体类1
2public interface BrandMapper extends Mapper<Brand> {
}
2.4. jdbc.properties
1 | jdbc.driver=com.mysql.jdbc.Driver |
2.5. MyBatis配置文件mybatis-config.xml
1 |
|
2.6. applicationContext.xml
在Spring和MyBatis集成配置的基础上,只需要将org.mybatis.spring.mapper.MapperScannerConfigurer修改为tk.mybatis.spring.mapper.MapperScannerConfigurer即可
1 | <context:property-placeholder location="classpath:jdbc.properties"/> |
2.7. 测试
1 | ("classpath:applicationContext.xml") |