我认为Mybatis-Plus相对于Mybatis的优势或者说增强:
1.CRUD 接口,基础的方法都已包装好
2.Wrapper 条件构造器,可解决大部分复杂任务,从sql解脱
3.丰富好用的插件扩展,比如分页,逻辑删除,性能分析
测试所需的数据库
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
1.添加Maven的mybatis-plus依赖
com.baomidou
mybatis-plus-boot-starter
3.1.2
注意:引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。
2.Mybatis-Plus配置类 (MybatisPlusConfig.class)
- 在Mybatis-Plus配置类中添加 @MapperScan 注解,扫描 Mapper 文件夹
- @EnableTransactionManagement开启事务管理的注解 @Transactional,一般用于service层,被注解的方法内操作是在一个事务里,只要其中有一个操作有异常,都会自动回滚。proxyTargetClass = true指定强制使用CGLIB代理。不加这个可能会出现JDK代理和CGLIB代理错误
- 你也可以不创建配置类,直接在Spring Boot 启动类中添加这两个注解和扩展插件的bean,不过建议分离,使用Mybatis-Plus配置类
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)//开启事务,强制使用CGLIB代理,可选
@MapperScan("com.sun.demo.mapper") //设置mapper接口的扫描包,必要
public class MybatisPlusConfig {
}
Spring在扫描注解时,取消了扫描抽象类和接口,所以无法找到你用@reponsitory注解的dao接口,虽然在引用时看似可以注入,但是实际上不可以使用,并没有作为bean交给spring,所以必须使用@Mapper去注解,将Dao交给spring,并且在编译时会为其创建实现类。但是如果每一给mapper都添加@mapper注解会很麻烦,这时可以使用@MapperScan注解来扫描包。
3.对应User实体类 User.java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
@Data注解会给此类默认提供Getter,Setter,equals,hashCode,toString方法
4.编写Mapper类 UserMapper.java
public interface UserMapper extends BaseMapper {
}
这只是最简单的配置,当mapper接口继承BaseMapper时,就会有了mybatis-plus最有用,最强大的Mapper CRUD 接口,大部分增删改查都可以利用此接口里方法完成
CRUD 接口参考:https://mp.baomidou.com/guide/crud-interface.html#mapper-crud-%E6%8E%A5%E5%8F%A3
5.编写对应的UserMapper,xml
现在我们在/src/main/resources/mapper下写对应的mapper.xml,来编写自己自定义的sql,不然只能使用Mybatis-plus提供的方法
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootmybatisplusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
}
测试结果
----- selectAll method test ------
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
这是最简单的,但是也挺够用的
下面谈一下mybatis-plus的插件,列举了
分页插件
1.在 Mybatis-Plus配置类(或者Spring Boot 启动类)中添加分页插件的bean
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)//开启事务,强制使用CGLIB代理,可选
@MapperScan("com.sun.demo.mapper") //设置mapper接口的扫描包,必要
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
测试类中添加测试方法
//分页查询
@Test
public void testselectPage() {
Page page = new Page<>(1, 2);
IPage userIPage = this.userMapper.selectPage(page, null);
System.out.println("总条数 ------> " + userIPage.getTotal());
System.out.println("当前页数 ------> " + userIPage.getCurrent());
System.out.println("当前每页显示数 ------> " + userIPage.getSize());
List records = userIPage.getRecords();
for (User user : records) {
System.out.println(user);
}
}
执行结果
总条数 ------> 85
当前页数 ------> 1
当前每页显示数 ------> 2
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
逻辑删除
就是删除不是真的从数据库删除,而是更改记录的某个字段来实现逻辑删除,比如deleted字段的0就是未删除,1就是删除
在配置文件application.properties中添加
#使用mp自带方法删除和查找都会附带逻辑删除功能 (自己写的xml不会)
# 逻辑已删除值(默认为 1),逻辑未删除值(默认为 0),也可以设置自己的标准,比如true和false
mybatis-plus.global-config.db-config.logic-delete-value: 1
mybatis-plus.global-config.logic-not-delete-value: 0
在数据库添加deleted列,项目中user中添加字段deleted,表示逻辑删除,并且添加@TableLogic注解来表示此字段为逻辑删除字段
@TableLogic
private Integer deleted;
测试类中添加测试方法
//删除数据
@Test
public void testDelete(){
this.userMapper.deleteById(1L);
System.out.println("删除成功!");
}
测试结果
删除成功!
进入数据库,查看id为1的记录,发现没有删除,而是此记录的deleted字段已经修改为1了,实现了逻辑删除
执行 SQL 分析打印
该功能依赖 p6spy 组件,完美的输出打印 SQL 及执行时长 3.1.0 以上版本
1.Maven:
p6spy
p6spy
3.8.3
2.修改application.properties
将之前的mysql的驱动和URL改为p6spy 提供的驱动类和格式
# mysql
spring.datasource.url: jdbc:p6spy:mysql://localhost:3306/mybatisplus?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
spring.datasource.driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#spring.datasource.url: jdbc:mysql://localhost:3306/mybatisplus?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
#spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.username: root
spring.datasource.password: 123456
3.添加spy.properties 配置
就添加到/src/main/resources下,和application.properties同一等级,可直接复制
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,batch,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
logMessageFormat和appender不要动,就保持这个,我之前以为com.baomidou.mybatisplus是别人的项目结构,就改为了自己的com.sun.demo,后面发现是固定的
在测试类中执行测试方法
//条件查询,这里是无条件
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
测试结果
----- selectAll method test ------
Consume Time:10 ms 2019-07-24 20:26:08
Execute SQL:SELECT ID,name,age,email,deleted FROM user WHERE deleted=0
User(id=1, name=Jone, age=18, [email protected], deleted=0)
User(id=2, name=Jack, age=20, [email protected], deleted=0)
User(id=3, name=Tom, age=28, [email protected], deleted=0)
User(id=4, name=Sandy, age=21, [email protected], deleted=0)
User(id=5, name=Billie, age=24, [email protected], deleted=0)
输出了sql语句,时间,还有耗时,很不错
这是其配置参数,参考
spring:
......
mybatis-plus:
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
#logic-delete-value: 0
#logic-not-delete-value: 1
#自定义填充策略接口实现
#meta-object-handler: com.umeox.waas.domain.handler.MyMetaObjectHandler
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true #entity类字段名映射表字段名
cache-enabled: false
<--完-->