0


【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus

文章目录

一、什么是 Mybatis Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、Spring Boot 3.0 集成 Mybatis Plus

1、 添加依赖

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.6</version></dependency><!-- mybatis plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.5</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>3.0.3</version></dependency>

注意: SpringBoot 3.0 需要 mybatis-spring 3.0.X 版本,否则会报如下错误:

Invalid value type for attribute 'factoryBeanObjectType'‘': java.lang.String

2、配置数据源

# druid 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_db?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.maxActive=20
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.stat-view-servlet.allow=true
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/druid/*
spring.datasource.druid.filters=stat,wall,slf4j
spring.datasource.druid.connectionProperties=druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000

# --- mybatis-plus start
mybatis-plus.mapper-locations=classpath:/org/shi9/module/**/xml/*Mapper.xml
# 关闭MP3.0自带的banner
mybatis-plus.global-config.banner=false
# 主键类型  0:"数据库ID自增",1:"该类型为未设置主键类型", 2:"用户输入ID",3:"全局唯一ID (数字类型唯一ID)", 4:"全局唯一ID UUID",5:"字符串全局唯一ID (idWorker 的字符串表示)";
mybatis-plus.global-config.db-config.id-type=ASSIGN_ID
# 返回类型为Map,显示null对应的字段
mybatis-plus.configuration.call-setters-on-nulls=true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# --- mybatis-plus end

3、创建实体类和 Mapper

创建你的实体类和对应的 Mapper 接口。MyBatis Plus 会自动扫描这些类并为你生成相应的 Mapper 和 SQL 语句。你也可以使用 MyBatis Plus 的 CRUD 操作来简化开发。

这里以

SysLog

为例

SysLogMapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="org.shi9.module.system.mapper.SysLogMapper"></mapper>

SysLogMapper.java

@MapperpublicinterfaceSysLogMapperextendsBaseMapper<SysLog>{}

4、编写 Service 类

publicinterfaceISysLogServiceextendsIService<SysLog>{}@ServicepublicclassSysLogServiceImplextendsServiceImpl<SysLogMapper,SysLog>implementsISysLogService{}

5、编写测试类

@Slf4j@SpringBootTestpublicclassSysLogServiceTest{@AutowiredprivateISysLogService sysLogService;@TestpublicvoidfindTotal(){Long total = sysLogService.count();System.out.println(total);}}

三、Mybatis Plus 查询示例

1、普通查询

以下是使用 MyBatis Plus 进行查询的示例:

  1. 根据主键查询单个结果

使用

selectById

方法查询单个结果:

User user = userMapper.selectById(1L);
  1. 查询多条记录

使用

selectList

方法查询多条记录:

List<User> users = userMapper.selectList(null);
  1. 使用 QueryWrapper 进行查询

可以使用

QueryWrapper

对查询条件进行组装:

QueryWrapper<User> queryWrapper =newQueryWrapper<>();
queryWrapper.eq("name","John").lt("age",30);List<User> userList = userMapper.selectList(queryWrapper);
  1. 分页查询

使用

Page

类进行分页查询:

Page<User> page =newPage<>(1,10);// 第1页,每页显示10条记录QueryWrapper<User> queryWrapper =newQueryWrapper<>();
queryWrapper.eq("name","John");
page.setFilter(queryWrapper);Page<User> result = userMapper.selectPage(page,null);
  1. 模糊查询

使用

like

方法进行模糊查询:

QueryWrapper<User> queryWrapper =newQueryWrapper<>();
queryWrapper.like("name","Jo");List<User> userList = userMapper.selectList(queryWrapper);
  1. 排序查询

使用

orderBy

方法进行排序查询:

QueryWrapper<User> queryWrapper =newQueryWrapper<>();
queryWrapper.orderByDesc("age");List<User> userList = userMapper.selectList(queryWrapper);
  1. 聚合查询

使用

groupBy

sum

count

等方法进行聚合查询:

QueryWrapper<User> queryWrapper =newQueryWrapper<>();
queryWrapper.groupBy("age");Long totalCount = userMapper.selectSum(queryWrapper,"age");
  1. 自定义 SQL

使用

@Select

注解自定义 SQL 语句:

@Select("SELECT * FROM user WHERE age > #{age}")List<User>selectUsersByAge(@Param("age")Integer age);

这些示例只是 MyBatis Plus 提供的一些常见查询方法的冰山一角。MyBatis Plus 还提供了很多其他功能和扩展,可以根据需要进行配置和使用。同时,MyBatis Plus 还支持与其他组件的集成,例如分页插件、乐观锁插件等,可以帮助你更加高效地进行数据库操作。

2、分页查询

MyBatis Plus 支持分页功能,可以通过配置分页插件来实现。分页插件可以帮助我们自动处理分页相关的 SQL 语句,简化分页逻辑。以下是使用分页插件的步骤:

1、配置分页插件

@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){MybatisPlusInterceptor interceptor =newMybatisPlusInterceptor();// 配置分页插件
    interceptor.addInnerInterceptor(newPaginationInnerInterceptor());// 增加@Version乐观锁支持
    interceptor.addInnerInterceptor(newOptimisticLockerInnerInterceptor());return interceptor;}

2. 使用分页插件

在 Mapper 接口或 XML 映射文件中使用分页插件提供的查询方法进行分页查询。例如:

@Select("SELECT * FROM user WHERE 1=1")Page<User>selectUserPage(Page<User> page);

在查询方法上使用

Page

参数,MyBatis Plus 会自动处理分页相关的 SQL 语句,返回包含分页信息的

Page

对象。你可以根据需要配置查询条件、排序规则等。

3. 处理分页结果

根据返回的

Page

对象,你可以获取当前页的数据、总记录数、总页数等信息,进行相应的业务处理。例如:

Page<User> page = userMapper.selectUserPage(newPage<>(1,10));// 第1页,每页显示10条记录List<User> userList = page.getRecords();// 当前页的数据列表int totalCount = page.getTotal();// 总记录数int totalPage = page.getPages();// 总页数

通过这些步骤,你可以在 MyBatis Plus 中配置和使用分页插件,简化分页逻辑,提高开发效率。

参考

  • Mybatis Plus

本文转载自: https://blog.csdn.net/wlddhj/article/details/135755585
版权归原作者 顽石九变 所有, 如有侵权,请联系我们删除。

“【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus”的评论:

还没有评论