MyBatis通用Mapper和PageHelper的过程代码解析

作者:袖梨 2020-11-05

本篇文章小编给大家分享一下MyBatis通用Mapper和PageHelper的过程代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

如果项目中使用到了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中引入:



  org.mybatis.spring.boot
  mybatis-spring-boot-starter
  1.3.1



  tk.mybatis
  mapper-spring-boot-starter
  1.1.5



  com.github.pagehelper
  pagehelper-spring-boot-starter
  1.2.3

接着在pom中配置MyBatis Geneator:


  
    
      org.mybatis.generator
      mybatis-generator-maven-plugin
      1.3.5
      
        
          
          com.oracle
          ojdbc6
          6.0
        
        
          tk.mybatis
          mapper
          3.4.0
        
      
      
        
          Generate MyBatis Artifacts
          package
          
            generate
          
        
      
      
        
        true
        
        true
        
        src/main/resources/mybatis-generator.xml
      
    
  

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

配置插件

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

mybatis:
 # type-aliases扫描路径
 type-aliases-package: com.springboot.bean
 # mapper xml实现扫描路径
 mapper-locations: classpath:mapper/*.xml
 property:
  order: BEFORE

接下来开始配置插件。

配置通用Mapper

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

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

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

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

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MyMapper extends Mapper, MySqlMapper {
	
}

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

配置PageHelper

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

#pagehelper
pagehelper: 
 helperDialect: oracle
 reasonable: true
 supportMethodsArguments: true
 params: count=countSql

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

配置Geneator*

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




  

    
      
      
      
      
    

    
    
      
      
      
    

    
    
    

    
      
    

    
    
      
      
    

    
    
      
    

    
    
    
      
    

    
    
    

相关文章

精彩推荐