MybatisPlus的各种功能使用笔记综合!

前端之家收集整理的这篇文章主要介绍了MybatisPlus的各种功能使用笔记综合!前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

官方文档:https://mybatis.plus/

官方样例地址:https://gitee.com/baomidou/mybatis-plus-samples

零、MybatisPlus特性:

一、快速开始

前置准备:本文所有代码样例包括数据库脚本均已上传至码云:https://gitee.com/tqbx/springboot-samples-learn

  1. 引入依赖
  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-boot-starter</artifactId>
  4. <version>3.4.0</version>
  5. </dependency>
  1. 配置yml
  1. spring:
  2. # MysqL数据库连接
  3. datasource:
  4. driver-class-name: com.MysqL.cj.jdbc.Driver
  5. url: jdbc:p6spy:MysqL://localhost:3306/eblog?serverTimezone=GMT%2B8
  6. username: xxx
  7. password: xxx
  8. # mybatis配置
  9. mybatis-plus:
  10. mapper-locations:
  11. - classpath*:mapper/*.xml
  12. # logging
  13. logging:
  14. level:
  15. root: warn
  16. com.hyh.mybatisplus.mapper: trace
  17. pattern:
  18. console: '%p%m%n'
  1. 编写MybatisPlus的配置
  1. @Configuration
  2. @MapperScan("com.hyh.mybatisplus.mapper")
  3. public class MybatisPlusConfig {
  4. }
  1. 编写测试方法
  1. @Test
  2. void selectById() {
  3. User user = mapper.selectById(1087982257332887553L);
  4. System.out.println(user);
  5. }

二、常用注解

当遇到不可抗拒因素导致数据库表与实体表名或字段名不对应时,可以使用注解进行指定。

  1. @Data
  2. @ToString
  3. @TableName("user") //指定表名 也可以使用table-prefix
  4. public class User {
  5. @TableId //指定主键
  6. private Long id;
  7. @TableField("name") //指定字段名
  8. private String name;
  9. private String email;
  10. private Integer age;
  11. private Long managerId;
  12. @TableField("create_time")
  13. private Date createTime;
  14. @TableField(exist = false)//备注[数据库中无对应的字段]
  15. private String remark;
  16. }

三、排除非表字段的三种方式

假设实体中存在字段且该字段只是临时为了存储某些数据,数据库表中并没有,此时有三种方法可以排除这类字段。

  1. 使用transient修饰字段,此时字段无法进行序列化,有时会不符合需求。
  2. 使用static修饰字段,此时字段就归属于类了,有时不符合需求。

以上两种方式在某种意义下,并不能完美解决这个问题,为此,mp提供了下面这种方式:

  1. @TableField(exist = false)//备注[数据库中无对应的字段]
  2. private String remark;

四、MybatisPlus的查询

博客地址:https://www.cnblogs.com/summerday152/p/13869233.html

代码样例地址:spring-boot-mybatis-plus学习

五、分页插件使用

文档地址:分页插件使用

我们这里采用SpringBoot的注解方式使用插件

  1. @Configuration
  2. @MapperScan("com.hyh.mybatisplus.mapper")
  3. public class MybatisPlusConfig {
  4. /**
  5. * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
  6. */
  7. @Bean
  8. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  9. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  10. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MysqL));
  11. return interceptor;
  12. }
  13. @Bean
  14. public ConfigurationCustomizer configurationCustomizer() {
  15. return configuration -> configuration.setUseDeprecatedExecutor(false);
  16. }
  17. }

测试分页

  1. @Test
  2. public void selectPage(){
  3. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  4. queryWrapper.ge("age",26);
  5. //Page<User> page = new Page<>(1,2);
  6. Page<User> page = new Page<>(1,2,false);
  7. Page<User> p = mapper.selectPage(page,queryWrapper);
  8. System.out.println("总页数: " + p.getPages());
  9. System.out.println("总记录数: " + p.getTotal());
  10. List<User> records = p.getRecords();
  11. records.forEach(System.out::println);
  12. }

七、MyBatisPlus代码生成器整合

文档地址:MyBatisPlus代码生成器整合

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

  1. 添加代码生成器依赖
  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-generator</artifactId>
  4. <version>3.4.0</version>
  5. </dependency>

八、ActiveRecord模式

  1. 实体类需要继承Model类。
  2. mapper继承BaseMapper。
  3. 可以将实体类作为方法调用者。
  1. @Test
  2. public void selectById(){
  3. User user = new User();
  4. User selectById = user.selectById(1319899114158284802L);//新对象
  5. System.out.println(selectById == user); //false
  6. System.out.println(selectById);
  7. }

九、主键策略

博客地址:MybatisPlus的各种支持的主键策略!

十、MybatisPlus的配置

文档地址:https://mybatis.plus/config/#基本配置

Springboot的使用方式

  1. mybatis-plus:
  2. ......
  3. configuration:
  4. ......
  5. global-config:
  6. ......
  7. db-config:
  8. ......

mapperLocations

  • 类型:String[]
  • 默认值:["classpath*:/mapper/**/*.xml"]

MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。

Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件

十一、通用Service

  1. /**
  2. * Service接口,继承IService
  3. * @author Summerday
  4. */
  5. public interface UserService extends IService<User> {
  6. }
  7. /**
  8. * Service实现类,继承ServiceImpl,实现接口
  9. * @author Summerday
  10. */
  11. @Service
  12. public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
  13. }
  14. @RunWith(SpringRunner.class)
  15. @SpringBootTest
  16. public class ServiceTest {
  17. @Autowired
  18. UserService userService;
  19. /**
  20. * 链式查询
  21. */
  22. @Test
  23. public void chain() {
  24. List<User> users = userService
  25. .lambdaQuery()
  26. .gt(User::getAge,25)
  27. .like(User::getName,"雨")
  28. .list();
  29. for (User user : users) {
  30. System.out.println(user);
  31. }
  32. }
  33. }

十二、逻辑删除功能

博客地址:MybatisPlus的逻辑删除功能使用!

十三、自动填充

博客地址:MybatisPlus的自动填充功能使用!

十四、乐观锁插件

博客地址:MybatisPlus的乐观锁插件使用!

十五、sql分析打印

地址: 执行 SQL 分析打印,该插件性能损耗,不建议生产环境使用。

  1. 引入maven依赖
  1. <dependency>
  2. <groupId>p6spy</groupId>
  3. <artifactId>p6spy</artifactId>
  4. <version>最新版本</version>
  5. </dependency>
  1. 配置application.yml
  1. spring:
  2. datasource:
  3. driver-class-name: com.p6spy.engine.spy.P6SpyDriver #p6spy 提供的驱动类
  4. url: jdbc:p6spy:MysqL://localhost:3306/eblog?serverTimezone=GMT%2B8 #url 前缀为 jdbc:p6spy
  5. ...
  1. spy.properties配置
  1. #3.2.1以上使用
  2. modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
  3. #3.2.1以下使用或者不配置
  4. #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
  5. # 自定义日志打印
  6. logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
  7. #日志输出到控制台
  8. appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
  9. # 使用日志系统记录 sql
  10. #appender=com.p6spy.engine.spy.appender.Slf4JLogger
  11. # 设置 p6spy driver 代理
  12. deregisterdrivers=true
  13. # 取消JDBC URL前缀
  14. useprefix=true
  15. # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
  16. excludecategories=info,resultset
  17. # 日期格式
  18. dateformat=yyyy-MM-dd HH:mm:ss
  19. # 实际驱动可多个
  20. #driverlist=org.h2.Driver
  21. # 是否开启慢sql记录
  22. outagedetection=true
  23. # 慢sql记录标准 2 秒
  24. outagedetectioninterval=2

如何在控制台打印sql语句的执行结果?

  1. <== Columns: id,content,authorAvatar
  2. <== Row: 2,<<BLOB>>,/res/images/avatar/0.jpg
  3. <== Row: 1,/res/images/avatar/default.png
  4. <== Total: 2

配置mybatis-plus.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl

十六、多租户的使用

博客地址:MybatisPlus的多租户插件使用!

十七、动态表名

添加配置 DynamicTableNameInnerInterceptor

  1. @Configuration
  2. @MapperScan("com.baomidou.mybatisplus.samples.dytablename.mapper")
  3. public class MybatisPlusConfig {
  4. @Bean
  5. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  6. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  7. DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
  8. HashMap<String,TableNameHandler> map = new HashMap<String,TableNameHandler>(2) {{
  9. put("user",(sql,tableName) -> {
  10. String year = "_2018";
  11. int random = new Random().nextInt(10);
  12. if (random % 2 == 1) {
  13. year = "_2019";
  14. }
  15. return tableName + year;
  16. });
  17. }};
  18. dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
  19. interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
  20. return interceptor;
  21. }
  22. }

测试随机访问user_2018和user_2019

  1. @SpringBootTest
  2. class SampleTest {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Test
  6. void test() {
  7. // 自己去观察打印 sql 目前随机访问 user_2018 user_2019 表
  8. for (int i = 0; i < 6; i++) {
  9. User user = userMapper.selectById(1);
  10. System.err.println(user.getName());
  11. }
  12. }
  13. }

十八、sql注入器

博客地址:MybatisPlus的sql注入器使用!

猜你在找的Mybatis相关文章