mybatis plus 是对 mybatis 的增强,自从用了 mybatis plus ,开发效率更快了。
今天来讲讲 SpringBoot 整合 mybatis plus。示例实现了:ActiveRecord、代码生成、分页、公共字段自动填充、逻辑删除、注入自定义 SQL、多租户 SQL 解析器功能。本教程使用的是 mybatis plus2.x 版本。
这边列出主要的配置和类,具体的项目可以查看源码。
整体结构
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> 类:
UserService 接口要继承 IService<User> 类:
UserServiceImpl 类要继承 ServiceImpl<UserMapper, User> 类:
配置
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 是单元测试类,里面有一些测试方法。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于