如果项目中使用到了MyBatis框架,那么使用通用Mapper和PageHelper分页插件将极大的简化我们的操作。通用Mapper可以简化对单表的CRUD操作,PageHelper分页插件可以帮我们自动拼接分页SQL,并且可以使用MyBatis Geneator来自动生成实体类,Mapper接口和Mapper xml代码,非常的方便。插件地址及作者链接https://gitee.com/free

引入依赖

这里使用Spring Boot来构建,可参考Spring-Boot中使用Mybatis.html搭建一个Spring boot + MyBatis的框架,然后在pom中引入:

  1. <!-- mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>2.2.0</version>
  6. </dependency>
  7. <!-- 通用mapper -->
  8. <dependency>
  9. <groupId>tk.mybatis</groupId>
  10. <artifactId>mapper-spring-boot-starter</artifactId>
  11. <version>2.0.2</version>
  12. </dependency>
  13. <!-- pagehelper 分页插件 -->
  14. <dependency>
  15. <groupId>com.github.pagehelper</groupId>
  16. <artifactId>pagehelper-spring-boot-starter</artifactId>
  17. <version>1.2.13</version>
  18. </dependency>

接着在pom中配置MyBatis Geneator:MyBatis Generator官方文档

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.mybatis.generator</groupId>
  5. <artifactId>mybatis-generator-maven-plugin</artifactId>
  6. <version>1.3.7</version>
  7. <dependencies>
  8. <dependency>
  9. <!-- 数据库连接驱动 -->
  10. <groupId>com.oracle.database.jdbc</groupId>
  11. <artifactId>ojdbc8</artifactId>
  12. <version>21.1.0.0</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>tk.mybatis</groupId>
  16. <artifactId>mapper</artifactId>
  17. <version>3.4.0</version>
  18. </dependency>
  19. </dependencies>
  20. <executions>
  21. <execution>
  22. <id>Generate MyBatis Artifacts</id>
  23. <phase>package</phase>
  24. <goals>
  25. <goal>generate</goal>
  26. </goals>
  27. </execution>
  28. </executions>
  29. <configuration>
  30. <!--允许移动生成的文件 -->
  31. <verbose>true</verbose>
  32. <!-- 是否覆盖,如果不加这个设置会导致每次运行都会在原目录再次创建 -->
  33. <overwrite>true</overwrite>
  34. <!-- 自动生成的配置 -->
  35. <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
  36. </configuration>
  37. </plugin>
  38. </plugins>
  39. </build>

src/main/resources/mybatis-generator.xml为生成器的配置,下文会介绍到。

注:如果使用

  • spring-boot-2.0.0.RELEASE
  • mybatis-generator-maven-plugin-1.4.0

会报错

  1. Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.4.0:
  2. generate (default-cli) on project itoken-service-admin:
  3. Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:
  4. 1.4.0:generate failed:
  5. A required class was missing while executing org.mybatis.generator:
  6. mybatis-generator-maven-plugin:1.4.0:generate:
  7. org/mybatis/generator/api/dom/xml/Element

mybatis-generator-core-1.4.0.jar 用好压打开这个压缩文件进去看,它想找的那个类已经不见了。 都不是插件和jar不兼容,是这个jar自己和自己不兼容,jar自己要找的类自己没有提供。

降低该插件版本
mybatis-generator-maven-plugin_1.3.7

配置插件

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

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

接下来开始配置插件。

配置通用Mapper

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

  1. #mappers 多个接口时逗号隔开
  2. mapper:
  3. mappers: com.springboot.config.MyMapper
  4. not-empty: false
  5. identity: oracle

关于参数的说明,参考https://gitee.com/free/Mapper/blob/master/wiki/mapper3/2.Integration.md中的可配参数介绍

除此之外,我们需要定义一个MyMapper接口:

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

值得注意的是,该接口不能被扫描到,应该和自己定义的Mapper分开。自己定义的Mapper都需要继承这个接口。

配置PageHelper

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

  1. #pagehelper
  2. pagehelper:
  3. helperDialect: oracle
  4. reasonable: true
  5. supportMethodsArguments: true
  6. params: count=countSql

参数相关说明参考https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md中的分页插件参数介绍

配置Geneator*

在路径src/main/resources/下新建mybatis-generator.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <context id="oracle" targetRuntime="MyBatis3Simple" defaultModelType="flat">
  7. <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
  8. <!-- 该配置会使生产的Mapper自动继承MyMapper -->
  9. <property name="mappers" value="com.springboot.config.MyMapper" />
  10. <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
  11. <property name="caseSensitive" value="false"/>
  12. </plugin>
  13. <!-- 阻止生成自动注释 -->
  14. <commentGenerator>
  15. <property name="javaFileEncoding" value="UTF-8"/>
  16. <property name="suppressDate" value="true"/>
  17. <property name="suppressAllComments" value="true"/>
  18. </commentGenerator>
  19. <!-- 数据库链接地址账号密码 -->
  20. <jdbcConnection
  21. driverClass="oracle.jdbc.driver.OracleDriver"
  22. connectionURL="jdbc:oracle:thin:@localhost:1521:ORCL"
  23. userId="scott"
  24. password="6742530">
  25. </jdbcConnection>
  26. <javaTypeResolver>
  27. <property name="forceBigDecimals" value="false"/>
  28. </javaTypeResolver>
  29. <!-- 生成Model类存放位置 -->
  30. <javaModelGenerator targetPackage="com.springboot.bean" targetProject="src/main/java">
  31. <property name="enableSubPackages" value="true"/>
  32. <property name="trimStrings" value="true"/>
  33. </javaModelGenerator>
  34. <!-- 生成映射文件存放位置 -->
  35. <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
  36. <property name="enableSubPackages" value="true"/>
  37. </sqlMapGenerator>
  38. <!-- 生成Dao类存放位置 -->
  39. <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件的代码
  40. type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
  41. type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
  42. <javaClientGenerator type="XMLMAPPER" targetPackage="com.springboot.mapper" targetProject="src/main/java">
  43. <property name="enableSubPackages" value="true"/>
  44. </javaClientGenerator>
  45. <!-- 配置需要生成的表 -->
  46. <table tableName="T_USER" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
  47. <generatedKey column="id" sqlStatement="oralce" identity="true"/>
  48. </table>
  49. </context>
  50. </generatorConfiguration>

相关表如下

  1. CREATE TABLE "SCOTT"."T_USER" (
  2. "ID" number(48) NOT NULL ,
  3. "USERNAME" VARCHAR2(128) NOT NULL ,
  4. "PASSWD" VARCHAR2(128) NOT NULL ,
  5. "CREATE_TIME" date,
  6. "STATUS" VARCHAR2(24) NOT NULL
  7. );
  8. ALTER TABLE T_USER ADD CONSTRAINT PRIMARY KEY (ID);

更详细的说明可参考链接:

代码生成

配置好MyBatis Geneator后,在eclipse中运行命令mybatis-generator:generate

MyBatis通用Mapper和PageHelper - 图1

在IDEA中:

方式一:使用idea的maven插件直接快速生成
Screen Shot 2021-11-13 at 9.09.04 PM.png
方式二:在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件 :

  1. 选择配置edit configuration

MyBatis通用Mapper和PageHelper - 图3

  1. 创建maven运行项

MyBatis通用Mapper和PageHelper - 图4

  1. 配置命令 mybatis-generator:generate -e

MyBatis通用Mapper和PageHelper - 图5

  1. 运行

MyBatis通用Mapper和PageHelper - 图6

以下为自动成成的代码:

User:

  1. @Table(name = "T_USER")
  2. public class User {
  3. @Id
  4. @Column(name = "ID")
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;
  7. @Column(name = "USERNAME")
  8. private String username;
  9. @Column(name = "PASSWD")
  10. private String passwd;
  11. @Column(name = "CREATE_TIME")
  12. private Date createTime;
  13. @Column(name = "STATUS")
  14. private String status;
  15. ...
  16. }

因为这里数据库使用的是Oracle,其没有主键自动自增的功能,这里先将@GeneratedValue(strategy = GenerationType.IDENTITY)去掉,主键的生成下面会介绍到。生成的主键是BigDecimal类型的,我们将其改为Long类型。

这里建立一个自增序列供主键使用:

  1. CREATE SEQUENCE seq_user INCREMENT BY 1 START WITH 100 MAXVALUE 999999999
  2. NOCYCLE NOCACHE;

UserMapper:

  1. import com.springboot.bean.User;
  2. import com.springboot.config.MyMapper;
  3. public interface UserMapper extends MyMapper<User> {
  4. }

UserMapper.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.springboot.mapper.UserMapper">
  4. <resultMap id="BaseResultMap" type="com.springboot.bean.User">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <id column="ID" jdbcType="DECIMAL" property="id" />
  9. <result column="USERNAME" jdbcType="VARCHAR" property="username" />
  10. <result column="PASSWD" jdbcType="VARCHAR" property="passwd" />
  11. <result column="CREATE_TIME" jdbcType="TIMESTAMP" property="createTime" />
  12. <result column="STATUS" jdbcType="CHAR" property="status" />
  13. </resultMap>
  14. </mapper>

极其方便的说!

Mapper

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

为了获取到Oracle 中序列的值,我们定义一个SeqenceMapper接口:

  1. public interface SeqenceMapper {
  2. @Select("select ${seqName}.nextval from dual")
  3. Long getSequence(@Param("seqName") String seqName);
  4. }

因为这里仅介绍Mapper自带的CRUD方法,所以UserMapper接口中无需定义任何方法。

通用Service

我们可以定义一个通用的Service,在其中定义一些通用的方法:

IService:

  1. @Service
  2. public interface IService<T> {
  3. Long getSequence(@Param("seqName") String seqName);
  4. List<T> selectAll();
  5. T selectByKey(Object key);
  6. int save(T entity);
  7. int delete(Object key);
  8. int updateAll(T entity);
  9. int updateNotNull(T entity);
  10. List<T> selectByExample(Object example);
  11. }

其实现类BaseService:

  1. public abstract class BaseService<T> implements IService<T> {
  2. @Autowired
  3. protected Mapper<T> mapper;
  4. @Autowired
  5. protected SeqenceMapper seqenceMapper;
  6. public Mapper<T> getMapper() {
  7. return mapper;
  8. }
  9. @Override
  10. public Long getSequence(@Param("seqName") String seqName){
  11. return seqenceMapper.getSequence(seqName);
  12. }
  13. @Override
  14. public List<T> selectAll() {
  15. //说明:查询所有数据
  16. return mapper.selectAll();
  17. }
  18. @Override
  19. public T selectByKey(Object key) {
  20. //说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
  21. return mapper.selectByPrimaryKey(key);
  22. }
  23. @Override
  24. public int save(T entity) {
  25. //说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
  26. return mapper.insert(entity);
  27. }
  28. @Override
  29. public int delete(Object key) {
  30. //说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
  31. return mapper.deleteByPrimaryKey(key);
  32. }
  33. @Override
  34. public int updateAll(T entity) {
  35. //说明:根据主键更新实体全部字段,null值会被更新
  36. return mapper.updateByPrimaryKey(entity);
  37. }
  38. @Override
  39. public int updateNotNull(T entity) {
  40. //根据主键更新属性不为null的值
  41. return mapper.updateByPrimaryKeySelective(entity);
  42. }
  43. @Override
  44. public List<T> selectByExample(Object example) {
  45. //说明:根据Example条件进行查询
  46. //重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列
  47. return mapper.selectByExample(example);
  48. }
  49. }

接下来让UserService接口继承IService接口:

  1. public interface UserService extends IService<User>{
  2. }

其实现类UserServiceImpl:

  1. @Repository("userService")
  2. public class UserServiceImpl extends BaseService<User> implements UserService{
  3. }

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

测试

测试插入:

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringBootTest(classes = Application.class)
  3. public class ApplicationTest {
  4. @Autowired
  5. private UserService userService;
  6. @Test
  7. public void test() throws Exception {
  8. User user = new User();
  9. user.setId(userService.getSequence("seq_user"));
  10. user.setUsername("scott");
  11. user.setPasswd("ac089b11709f9b9e9980e7c497268dfa");
  12. user.setCreateTime(new Date());
  13. user.setStatus("0");
  14. this.userService.save(user);
  15. }
  16. }

运行代码,查看数据库:

MyBatis通用Mapper和PageHelper - 图7

测试查询:

  1. Example example = new Example(User.class);
  2. example.createCriteria().andCondition("username like '%i%'");
  3. example.setOrderByClause("id desc");
  4. List<User> userList = this.userService.selectByExample(example);
  5. for (User u : userList) {
  6. System.out.println(u.getUsername());
  7. }
  8. List<User> all = this.userService.selectAll();
  9. for (User u : all) {
  10. System.out.println(u.getUsername());
  11. }
  12. User user = new User();
  13. user.setId(1l);
  14. user = this.userService.selectByKey(user);
  15. System.out.println(Optional.ofNullable(user)
  16. .map(OraUser::getUsername)
  17. .orElse("NULL");

测试删除:

  1. User user = new User();
  2. user.setId(4l);
  3. this.userService.delete(user);

分页测试,从第二页开始,每页2条数据:

  1. PageHelper.startPage(2, 2);
  2. List<User> list = userService.selectAll();
  3. PageInfo<User> pageInfo = new PageInfo<User>(list);
  4. List<User> result = pageInfo.getList();
  5. for (User u : result) {
  6. System.out.println(u.getUsername());
  7. }

查看日志打印出的SQL:

  1. 2017-12-28 10:25:14.033 DEBUG 11116 --- [main] c.s.mapper.UserMapper.selectAll : ==> Preparing: SELECT * FROM ( SELECT TMP_PAGE.*, ROWNUM ROW_ID FROM (
  2. SELECT ID,USERNAME,PASSWD,CREATE_TIME,STATUS FROM T_USER ) TMP_PAGE WHERE ROWNUM <= ? ) WHERE ROW_ID > ?
  3. 2017-12-28 10:25:14.068 DEBUG 11116 --- [main] c.s.mapper.UserMapper.selectAll : ==> Parameters: 4(Integer), 2(Integer)
  4. 2017-12-28 10:25:14.073 DEBUG 11116 --- [main] c.s.mapper.UserMapper.selectAll : <== Total: 2

插件已经帮我自动拼接好了。其他注意事项参考官方说明。