【SpringBoot实战】之整合mybatis plus 2.0

  |   0 评论   |   4,695 浏览

mybatis plus是对mybatis的增强,自从用了mybatis plus ,开发效率更快了。

今天来讲讲SpringBoot整合mybatis plus。示例实现了:ActiveRecord、代码生成、分页、公共字段自动填充、逻辑删除、注入自定义SQL、多租户 SQL 解析器功能。本教程使用的是mybatis plus2.x版本。

这边列出主要的配置和类,具体的项目可以查看源码。

整体结构

imagepng

pom配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.cimu</groupId>
	<artifactId>mybatisplus2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatisplus2</name>
	<description>mybatisPlus2.0 project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

MybatisPlusConfig类:

@Configuration
@MapperScan("com.cimu.mybatisplus2.mapper*")
public class MybatisPlusConfig {

    /**
 * mybatis-plus SQL执行效率插件【生产环境可以关闭】 */  @Bean
  public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
  }

    /**
 * mybatis-plus分页插件
  * 文档:http://mp.baomidou.com
  */
  @Bean
  public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
  paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
 /* * 【测试多租户】 SQL 解析处理拦截器 * 这里固定写成住户 1 实际情况你可以从cookie读取,因此数据看不到 【 麻花藤 】 这条记录( 注意观察 SQL ) */  List sqlParserList = new ArrayList<>();
  TenantSqlParser tenantSqlParser = new TenantSqlParser();
  tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
  public Expression getTenantId() {
                return new LongValue(2L);
  }
            @Override
  public String getTenantIdColumn() {
                return "company";
  }
            @Override
  public boolean doTableFilter(String tableName) {
                // 这里可以判断是否过滤表
  return !"user".equals(tableName);
  }
        });
  sqlParserList.add(tenantSqlParser);
  paginationInterceptor.setSqlParserList(sqlParserList);
 return paginationInterceptor;
  }

    @Bean
  public MetaObjectHandler metaObjectHandler() {
        return new SolarMetaObjectHandler();
  }

    /**
 * 注入主键生成器 */  @Bean
  public IKeyGenerator dbKeyGenerator() {
        return new H2KeyGenerator();
  }

    /**
 * 注入sql注入器 */  @Bean
  public ISqlInjector sqlInjector() {
        return new MySqlInjector();
  }

    @Bean
  public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
  }

}

自定义方法
MySqlInjector类

public class MySqlInjector extends LogicSqlInjector {

    @Override
  public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class mapperClass,
  Class modelClass, TableInfo table) {
        /* 添加一个自定义方法 */
  deleteAll(mapperClass, modelClass, table);
  }

    public void deleteAll(Class mapperClass, Class modelClass, TableInfo table) {
        /* 执行 SQL ,动态 SQL 参考类 SqlMethod */
  String sql = "delete from " + table.getTableName();

  /* mapper 接口方法名一致 */
  String method = "deleteAll";
  SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
 this.addDeleteMappedStatement(mapperClass, method, sqlSource);
  }

}

自动填充配置类:

public class SolarMetaObjectHandler extends MetaObjectHandler {

    protected final static Logger logger = LoggerFactory.getLogger(SolarMetaObjectHandler.class);
 private static final String CREATE_TIME = "createTime";
 private static final String UPDATE_TIME = "updateTime";

  @Override
  public void insertFill(MetaObject metaObject) {
        logger.info("新增的时候干点不可描述的事情");
  Date now = new Date();
  Object createTimeObj = getFieldValByName(CREATE_TIME, metaObject);
 if (null == createTimeObj) {
            setFieldValByName(CREATE_TIME, now, metaObject);
  }
        preUpdate(metaObject, now);
  }

    @Override
  public void updateFill(MetaObject metaObject) {
        logger.info("更新的时候干点不可描述的事情");
  Date now = new Date();
  preUpdate(metaObject, now);
  }

    /**
 * 封装更新的统一处理 * * @param metaObject MetaObject
 * @param now Date
 */  private void preUpdate(MetaObject metaObject, Date now) {
        //强制维护时间
  setFieldValByName(UPDATE_TIME, now, metaObject);
  }

实体类user:

public class User extends Model{

    /**
 * 主键ID */  
 @TableId("id")
    private Long id;
  /**
 * 真实名称 */  
 private String realName;
  /**
 * 手机号码 */  
 private String mobile;
  /**
 * 密码 */  
 private String password;
  /**
 * 创建日期 */  
 @TableField(fill = FieldFill.INSERT)
    private Date createTime;
  /**
 * 修改日期 */  
 @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
  /**
 * 删除标记 1:删除;0:未删除 */  
 @TableLogic
  private String delFlag;
  @Version
  private Integer version;

 private Integer company;

 ...省略get/set方法

    @Override
  protected Serializable pkVal() {
        return this.id;
  }

}

UserMapper接口要继承BaseMapper<User>类:
imagepng

UserService接口要继承IService<User>类:
imagepng

UserServiceImpl类要继承ServiceImpl<UserMapper, User>类:
imagepng

配置

application.properties配置

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

mybatis-plus.global-config.refresh-mapper= true
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.global-config.logic-delete-value=1
mybatis-plus.global-config.logic-not-delete-value=0
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.global-config.sql-parser-cache=true

单元测试

Mybatisplus2ApplicationTests是单元测试类,里面有一些测试方法。

源码地址

也可以关注我的公众号,及时获取最新文章

本文为博主原创文章,未经博主允许不得转载。

评论

发表评论