一、Mybatis-Plus简介
Mybatis-Plus是一个Mybatis(opens new window)的增强工具,在Mybatis的基础上只做增强不做改变,为简化开发。
这里简单介绍,重点放在干货上, 开干!!!
二、SpringBoot整合Mybatis-Plus入门
(一)创建maven工程,添加 Mybatis-Plus所需的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 同时需要再 IDEA中下载 这个插件, 用于简化 实体类 开发 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql数据库连接依赖 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
<scope>runtime</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
(二)配置application.yml
server:
port: 8888
tomcat:
uri-encoding: UTF-8
spring:
datasource:
# 数据库连接池 实现方式:Druid 和 hikari: 如果对性能要求比较高,且对功能要求比较简单,可以选择HikariCP;如果对功能要求比较多,且对性能要求不是非常高,可以选择Druid。
# type: com.alibaba.druid.pool.DruidDataSource #明确指明使用druid
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver # mysql数据库 驱动(mysql-connector-java) 8版本及以上选择 该 cj配置
url: jdbc:mysql://127.0.0.1:3306/wtt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # sql语句输出到 终端
global-config:
db-config:
id-type: auto # 主键自增策略
# table-prefix: wtt_ # 设置 表的前置 公共 表名
(三)创建数据库表users
CREATE TABLE `users` (
`uid` bigint(32) NOT NULL AUTO_INCREMENT,
`nick_name` varchar(255) NOT NULL,
`age` tinyint(1) DEFAULT NULL,
`del_at` int(11) DEFAULT '0',
PRIMARY KEY (`uid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
(四)构建 数据模型 Users
@Data
// @TableName("users") // MybPls的注解,用来设置 实体类 对应的 表名,这里的优先级 大于 配置中 指定 公共前缀表名的优先级,即 这里指定是什么 表名 就是什么,谁都改不了
public class Users {
// MybPls的注解,用来设置 将对应的 字段 指定为 --->主键<--- id 对应数据表中的 uid,
// 在 MybPls中,在 增加操作是 主键 的 默认值 是 通过雪花算法得到的 19为Long数字, 通过 type = IdType.AUTO, 采用字段的 自增机制。
@TableId(value = "uid", type = IdType.AUTO)
private Long id;
@TableField("nick_name") // MybPls的注解,用来设置 指定属性对应的 字段名
private String nickName;
private Byte age;
@TableLogic // 设置 该字段为 逻辑删除 字段, 即 数据的删除操作 都变为 软删除。 删除之后 该字段为 值为 1
private Integer delAt; // 可以默认 对应为 数据表中的 del_at 字段
}
(五)编写SpringBoot启动类
/*
* 1、当前 Mapper所在的包
* 2、映射文件 所在的包
* */
@SpringBootApplication
@MapperScan({"com.zcdf.school.mapper"}) // 扫描Mapper接口 所在的包
@EnableAsync
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
(六)编写Dao层 的 mapper接口
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
(七)测试
@Autowired
private UsersMapper usersMapper;
@GetMapping("/test")
public List<?> test02(){
List<Long> list = Arrays.asList(1L,2L,3L,4L);
List<Users> users = usersMapper.selectBatchIds(list);
System.out.println(users);
return users;
}
三、CRUD
BaseMapper
接口方法介绍
- 增
// 插入一条记录
int insert(T entity);
- 删
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
- 改
// 根据 whereEntity 条件,更新记录
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
- 查
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
栗子
改
- updateById方法
根据id进行记录更新,如果对象属性未传值,则不会更新该字段,保持数据库表原来字段值
public void testUpdateById() {
Employee employee=new Employee();
employee.setEmpId(10)
employee.setName("刘龙");
employee.setEmpGender("女");
employee.setAge(23);
employee.setEmail("liulong@163.com");
employeeMapper.updateById(employee);
}
- update(entity,wrapper)方法
public void testdateById(){
//根据员工的名字,更新
Employee employee2=new Employee();
employee2.setEmpGender("男");
employee2.setAge(18);
employee2.setEmail("liulong@126.com");
employeeMapper.update(employee2,new UpdateWrapper<Employee>().eq("name","刘龙"));
}
查
- selectById方法
根据id查询指定记录
@Test
public void testSelectById() {
Employee employee=employeeMapper.selectById(1);
System.out.println(employee);
}
- selectBatchIds方法
批量查询指多个id的记录集合
@Test
public void testSelectBatchIds() {
List list= Arrays.asList(1,2,3);
List<Employee> employeeList = employeeMapper.selectBatchIds(list);
employeeList.forEach(System.out::println);
}
- selectByMap方法
根据Map集合中传入的条件进行查询,每个条件都是and关系
@Test
public void testSelectByMap() {
Map<String,Object> map=new HashMap<>();
map.put("emp_gender","男");
map.put("age",29);
List<Employee> employeeList = employeeMapper.selectByMap(map);
employeeList.forEach(System.out::println);
}
删
- deleteById方法
根据id删除记录
@Test
public void testDeleteById(){
int rows=employeeMapper.deleteById(1);
System.out.println("受影响的行数:"+rows);
}
- deleteByMap方法
根据Map中的条件进行删除,map中的条件在sql语句中是and关系
@Test
public void testDeleteByMap(){
Map<String,Object> map=new HashMap<>();
map.put("emp_gender","男");
map.put("emp_name","刘辉");
int rows=employeeMapper.deleteByMap(map);
System.out.println("受影响的行数:"+rows);
}
- deletebatchIds方法
根据传入List集合中的id进行批量删除
@Test
public void testDeleteBatchIds(){
List list= Arrays.asList(4,7,1);
int rows=employeeMapper.deleteBatchIds(list);
System.out.println("受影响的行数:"+rows);
}
四、常用注解
1、@TableId注解
描述:主键注解
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | " " | 主键字段名 |
type | Enum | 否 | IdType.NONE | 主键类型 |
IdType
值 | 描述 |
Auto | 数据库ID自增 |
None | 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于Input) |
Input | Insert前自行set主键值 |
ASSIGN_ID
|
分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator 的方法 nextId (默认实现类为DefaultIdentifierGenerator 雪花算法)
|
ASSIGN_UUI
|
分配UUID,主键类型为String(since 3.3.0),使用接口 IdentifierGenerator 的方法 nextUUID (默认default方法)
|
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Employee {
//使用数据库自增策略
//@TableId(type=IdType.AUTO)
//默认使用雪花算法生成数字
@TableId
private Long empId;
private String empName;
private String empGender;
private Integer age;
private String email;
}
2、@TableName注解
描述:表名注解
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 表名 |
schema | String | 否 | "" | schema |
keepGlobalPrefix | boolean | 否 | false |
是否保持使用全局的tablePrefix 的值 (如果设置了全局tablePrefix 且自行设置了 value 的值)
|
resultMap | String | 否 | "" | xml中resultMap的id |
AutoResultMap | boolean | 否 | false |
是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入)
|
excludeProperty | String[] | 否 | {} | 需要排除的属性名(@since 3.3.1) |
当表名跟实体类类名不一致时,要使用@TableName注解进行映射
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
@TableName(value = "tb_employee")
public class Employee {
//使用数据库自增策略
//@TableId(type=IdType.AUTO)
//默认使用雪花算法生成数字
@TableId
private Long empId;
private String empName;
private String empGender;
private Integer age;
private String email;
}
3、@TableField注解
描述:字段注解(非主键)
属性 | 类型 | 必须指定 | 默认值 | 描述 |
value | String | 否 | "" | 数据库字段名 |
el | String | 否 | "" |
映射为原生 #{ ... } 逻辑,相当于写在
xml 里的 #{ ... } 部分
|
exist | boolean | 否 | true | 是否为数据库表字段 |
condition | String | 否 | "" |
字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s}
|
update | String | 否 | "" |
字段 update set 部分注入, 例如:
update="%s+1":表示更新时会set
version=version+1(该属性优先级高于
el 属性)
|
insertStrategy | Enum | N | DEFAULT |
举例:NOT_NULL: insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null"># {columnProperty}</if>)
|
updateStrategy | Enum | N | DEFAULT |
举例:IGNORED: update table_a set column=#{columnProperty}
|
whereStrategy | Enum | N | DEFAULT |
举例:NOT_EMPTY: where <if test="columnProperty != null and columnProperty!=''">column=# {columnProperty}</if>
|
fill | Enum | 否 | FieldFill.DEFAULT | 字段自动填充策略 |
Select | boolean | 否 | true | 是否进行select查询 |
keepGlobalFormat
|
boolean
|
否
|
false
|
是否保持使用全局的 format 进行处理
|
jdbcType
|
JdbcType
|
否
|
JdbcType.UNDEFINE
|
JDBC类型 (该默认值不代表会按照该值生效)
|
typeHandler
|
Class<?extends TypeHandler>
|
否
|
UnknownTypeHandler.class
|
类型处理器 (该默认值不代表会按照该值生效)
|
numericScale
|
String
|
否
| "" |
指定小数点后保留的位数
|
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
@TableName(value = "tb_employee")
public class Employee {
@TableId
private Long empId;
//当表中的列与实体类属性不一致时,使用TableField指定数据库中的列名
@TableField(value = "emp_name")
private String name;
private String empGender;
private Integer age;
private String email;
//当表中没有remark时,使用TableField的exist=false属性忽略该字段
@TableField(exist = false)
private String remark;
}
4、@TableLogic注解
设置 指定字段为 逻辑删除
字段, 即 数据的删除操作 都变为 软删除。 删除之后 该字段为 值为 1。
public class Users {
private Long id;
@TableLogic
private Integer delAt;
}
五、Mybatis-Plus条件构造器
(一)条件构造器介绍
在mybatis-plus中提了 构造条件 的类 Wrapper
,它可以根据自己的意图定义我们需要的条件。
Wrapper是一个抽象类
,一般情况下我们用它的 子类
QueryWrapper
来实现自定义条件查询,用它的 子类
UpdateWrapper
进行更新操作。
(二)SelectOne方法
//查询姓名为刘辉军并且性别为男的员工
@Test
public void testSelectOne(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name","刘辉军");
queryWrapper.eq("sex","男");
Employee employee = employeeMapper.selectOne(queryWrapper);
System.out.println(employee);
}
(三)SelectList方法
//查询姓名中带有"磊"的并且年龄小于30的员工
@Test
public void testSelectList(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.like("name","磊").lt("age",30);
List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
employeeList.forEach(System.out::println);
}
//查询姓刘的或者性别为男,按年龄的除序排序
@Test
public void testSelectList2(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.like("name","王")
.or().eq("emp_gender","男")
.orderByDesc("age");
List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
employeeList.forEach(System.out::println);
}
//查询姓刘的并且(年龄小于35或者邮箱不为空)
@Test
public void testSelectList3(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.likeRight("name","刘")
.and(wq->wq.lt("age",35).or().isNotNull("email"));
List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
employeeList.forEach(System.out::println);
}
(四)SelectPage方法
SelectPage 用于分页,在Mybatis-Plus中分页有两种:一种是逻辑分页
或叫 内存分页,另一个是物理分页
。
内存分页就是把数据全部查询出来放到内容中,返回你想要的一部分数据,当数据量非常庞大时,这种方法就行不通了,因为太耗内容。
所以一般采用物理分页,需要SpringMVC中加入 物理分页配置:
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页插件:
interceptor.addInnerInterceptor(
// 因为 每个数据库的分页 机制是不一样的,所以这里需要指明 使用的是 Mysql数据库
new PaginationInnerInterceptor(DbType.MYSQL)
);
return interceptor;
}
}
@Test
public void testSelectPage(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.lt("age",50);
Page<Employee> page=new Page<>(1,2);
Page<Employee> employeePage = employeeMapper.selectPage(page, queryWrapper);
System.out.println("当前页:"+ employeePage.getCurrent());
System.out.println("每页记录数:"+employeePage.getSize());
System.out.println("总记录数:"+employeePage.getTotal());
System.out.println("总页数:"+employeePage.getPages());
List<Employee> employeeList = employeePage.getRecords();
employeeList.forEach(System.out::println);
}
(五)Select 不定条件
// ==========》 方式一 《=============
String name = "";
Integer age = 20;
QueryWrapper<Whero> queryWrapper = new QueryWrapper<>();
// 不定条件
if (StringUtils.isNotBlank(name)) {
queryWrapper.eq("name", name);
}
if (age != null) {
queryWrapper.eq("age", age);
}
List<Whero> wheros = wheroMapper.selectList(queryWrapper);
System.out.println(wheros);
// ==========》 方式二 简化写法 《=============
QueryWrapper<Whero> queryWrapper2 = new QueryWrapper<>();
// 不定条件
queryWrapper2.eq(StringUtils.isNotBlank(name), "name", name).eq(age != null, "age", age);
List<Whero> wheros2 = wheroMapper.selectList(queryWrapper2);
System.out.println(wheros2);
(六)Update
- QueryWrapper
QueryWrapper<Whero> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", 4).or().eq("name", "www");
Whero whero = new Whero();
whero.setName("李哈哈");
int n = wheroMapper.update( whero , queryWrapper);
System.out.println("更新的数据数位:" + n);
- UpdateWrapper
UpdateWrapper<Whero> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", 4).or().eq("name", "www");
updateWrapper.set("name", "李哈哈");
int n = wheroMapper.update(null, updateWrapper);
System.out.println("更新的数据数位:" + n);
(七)Delete方法
//根据姓名和年龄删除记录
@Test
public void testDelete(){
QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name","刘龙")
.eq("age",26);
int rows=employeeMapper.delete(queryWrapper);
System.out.println("受影响的行数:"+rows);
}
(八)Lambda 条件构造器
LambdaQueryWrapper<Whero> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Whero::getId, 6); // 原先的写法:queryWrapper.eq("id", 4);
List<Whero> wheros2 = wheroMapper.selectList(queryWrapper);
System.out.println(wheros2);
六、Mybatis-Plus的Service封装
(一)通用service简介
Mybatis-Plus除了 通用的Mapper 还有 通用的Servcie层。
使用建议: 当我们需要自定义 sql的查询方法时,还是需要通过 Mapper 进行自定义方法 到对应的 ***Mapper .xml文件中。 如果 我们在 做多数据源时, @DS 注解只能 跟 类 和 方法, 此时 建议是使用 通用的Servcie层。
(二)通用service常用方法介绍
/**
* 插入一条记录(选择字段,策略插入)
*
* @param entity 实体对象
*/
default boolean save(T entity) {
return SqlHelper.retBool(getBaseMapper().insert(entity));
}
/**
* 根据 ID 选择修改
*
* @param entity 实体对象
*/
default boolean updateById(T entity) {
return SqlHelper.retBool(getBaseMapper().updateById(entity));
}
/**
* TableId 注解存在更新记录,否插入一条记录
*
* @param entity 实体对象
*/
boolean saveOrUpdate(T entity);
/**
* 根据 Wrapper,查询一条记录 <br/>
* <p>结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT
1")</p>
*
* @param queryWrapper 实体对象封装操作类 {@link
com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
default T getOne(Wrapper<T> queryWrapper) {
return getOne(queryWrapper, true);
}
/**
* 根据 Wrapper,查询一条记录
*
* @param queryWrapper 实体对象封装操作类 {@link
com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
* @param throwEx 有多个 result 是否抛出异常
*/
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
(三)通用service的案例
1、构建service接口
IService
的使用
public interface UsersService extends IService<Users> {
}
2、构建service实现类
ServiceImpl
的使用
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper,Users> implements UsersService {
}
3、通用service测试
@Autowired
private UsersService usersService;
@GetMapping("/add")
public int add(){
// 批量添加
List<Users> usersList = new ArrayList<>();
for (int i=1;i<2;i++) {
Users users = new Users();
users.setNickName("tom" + i);
users.setAge((byte)(10+i));
usersList.add(users);
}
boolean res = usersService.saveBatch(usersList); // 说明: 这里的批量添加 仅仅是 代码层面的,实际上还是一条记录一次IO的形式添加的。
System.out.println("批量添加的结果是:" + res);
System.out.println(usersList);
return 123;
}
七、使用案例
1、搭配 pagehelper 实现分页
依赖
pom.xml
<!-- 这里用 mybatis-plus 的依赖, 来演示 Mybatis的使用 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</exclusion>
</exclusions>
</dependency>
配置
# Spring配置
spring:
# redis 配置
redis:
host:
port:
database:
password:
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
mybatis-plus:
# 指定实体类所在包的路径,MyBatis-Plus 会自动扫描该路径下的实体类
typeAliasesPackage: com.ruoyi.**.domain
# 指定 Mapper 接口所在包的路径,MyBatis-Plus 会自动扫描该路径下的 Mapper 接口
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 指定 MyBatis 全局配置文件的位置
# configLocation: classpath:mybatis/mybatis-config.xml
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
Dao层
public interface UsersMapper extends BaseMapper<Users> {
public List<UsersDto> getUserAllInfo(
@Param("nickname") String nickname,
@Param("uid") Integer uid,
@Param("tel") String tel
);
}
Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.UsersMapper">
<resultMap id="UserAllInfo" type="com.ruoyi.system.dto.UsersDto">
<id property="uid" column="uid" jdbcType="INTEGER"/>
<result property="avatar" column="avatar" jdbcType="VARCHAR"/>
<result property="createAt" column="create_at" jdbcType="INTEGER"/>
<result property="tel" column="tel" jdbcType="VARCHAR"/>
<result property="nickname" column="nickname" jdbcType="VARCHAR"/>
<result property="fee" column="fee" jdbcType="DECIMAL"/>
<result property="buyAt" column="buy_at" jdbcType="INTEGER"/>
<result property="bosAt" column="bos_at" jdbcType="INTEGER"/>
</resultMap>
<select id="getUserAllInfo" resultMap="UserAllInfo">
SELECT SQL_CALC_FOUND_ROWS u.uid, u.nickname, u.roles, u.tel, u.create_at , u.avatar , ub.fee, ur.buy_at , ur.bos_at from users u
left join users_balance ub
on u.uid = ub.uid
left join users_relation ur
on u.uid = ur.uid
<where>
<if test="nickname != null and nickname != ''">
and u.nickname like concat('%',#{nickname},'%')
</if>
<if test="uid != null and uid != 0">
and u.uid = #{uid}
</if>
<if test="tel != null and tel != ''">
and u.tel = #{tel}
</if>
</where>
order by u.uid desc
</select>
</mapper>
Controller层
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Autowired
private UsersMapper usersMapper;
@ApiOperation("用户基本信息列表")
@GetMapping("/test")
public AjaxResult test(@RequestParam(value = "uid",required = false) Integer uid,
@RequestParam(value = "nickname",required = false) String nickname,
@RequestParam(value = "tel",required = false) String tel,
@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
@RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize) {
// 启用 分页
PageHelper.startPage(pageNum, pageSize);
List<UsersDto> usersDto = usersMapper.getUserAllInfo2(nickname, uid, tel);
return AjaxResult.success(new PageInfo<>(usersDto));
}
@GetMapping("/test2")
public AjaxResult test2() {
// 启用 分页
PageHelper.startPage(1, 2);
LambdaQueryWrapper<Users> usersLambdaQueryWrapper = new LambdaQueryWrapper<>();
usersLambdaQueryWrapper.ne(Users::getUid, 0);
List<Users> usersList = usersMapper.selectList(usersLambdaQueryWrapper);
return AjaxResult.success(new PageInfo<>(usersList));
}
1-2、Mybatis-Plus 自带分页功能
1、配置类
@Configuration
public class MybatisPlusPageConfig {
/**
* 新的分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2、示例
public class UserServicePageTest extends Base {
@Autowired
private UserMapper mapper;
@Test
public void page() {
Page<UserDO> page = new Page<>(1, 3);
Page<UserDO> result = mapper.selectPage(page, new LambdaQueryWrapper<UserDO>().eq(UserDO::getDeleted, 0));
}
}
注意:
MybatisPlus 与 pagehelper 存在依赖 jsqlparser 冲突,不建议混用
2、逻辑删除功能
这个场景是这样的,因为我们在设计表结构的时候都会有一个逻辑删除字段,比如上表中就有一个**「deleted」**字段,1=删除 0=未删除。
那我们在查询或者更新操作时,sql都会带上这个字段。
例如:
-- 更新
update user set sex='女' where id = 1 and deleted=0
-- 查询
select id,sex,username from user where deleted=0
既然都要带上,那是不是可以做成全局的,不用我们每个sql都手动添加deleted=0,这个条件。
使用方法
「1、配置」
例如: application.yml
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名()
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
「2、实体类字段上加上@TableLogic注解」
@TableLogic
private Integer deleted;
注意
:since 3.3.0,配置后可以忽略不配置这步骤
示例
public class UserServiceDeleteTest extends Base {
@Autowired
private UserMapper mapper;
@Test
public void update() {
//方式一: 根据id更新
mapper.updateById(new UserDO().setId(1).setPhone("13312345678"));
//实际执行sql: UPDATE user SET phone=? WHERE id=? AND deleted=0
}
@Test
public void select() {
//1、根据主键获取
UserDO userDO = mapper.selectById(1);
//实际执行sql: SELECT id,username,phone,sex,create_time,update_time,deleted FROM user WHERE id=? AND deleted=0
}
}
上面两条sql虽然没有加入deleted=0这个条件,但因为加了全局配置,所以会自动加上deleted=0条件。
3、自动填充功能
1、使用背景
在设计表的时候,会有**「创建人ID」,「创建人名称」,「创建时间」,「更新人ID」,「更新人名称」,「更新时间」**。
我们在新增或者更新数据的时候,都会修改这些数据。所以我们也可以做成全局的。
2、使用方式
「1、实体添加注解」
/**
* 创建时间
*/
@TableField(value = "create_time",fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
FieldFill一共有4种属性,默认是DEFAULT
public enum FieldFill {
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE;
}
「2、自定义实现类 MyMetaObjectHandler」
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
//设置属性值
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
3、测试
@Test
public void insert() {
UserDO user = new UserDO();
user.setUsername("asdasds");
user.setPhone("1888");
user.setSex("女");
Assertions.assertThat(mapper.insert(user)).isGreaterThan(0);
// 成功直接拿回写的 ID
Assertions.assertThat(user.getId()).isNotNull();
}
用上面这个测试用例,发现虽然这里没有插入创建时间和更新时间,但打印sql发现插入该属性。
4、注意事项
-
填充原理是直接给
entity
的属性设置值!!! -
注解则是指定该属性在对应情况下必有值,如果无值则入库会是
null
-
MetaObjectHandler
提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null
则不填充 -
字段必须声明
TableField
注解,属性fill
选择对应策略,该声明告知Mybatis-Plus
需要预留注入SQL
字段 -
填充处理器
MyMetaObjectHandler
在 Spring Boot 中需要声明@Component
或@Bean
注入 -
update(T t,Wrapper updateWrapper)时t不能为空,否则自动填充失效
4、多 数据源
1、引入依赖
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- 多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2、配置文件
server:
port: 8886
tomcat:
uri-encoding: UTF-8
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql数据库 驱动(mysql-connector-java) 8版本及以上选择 该 cj配置
url: jdbc:mysql://127.0.0.1:39306/wtt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
slave_1:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql数据库 驱动(mysql-connector-java) 8版本及以上选择 该 cj配置
url: jdbc:mysql://127.0.0.1:3333/whero?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # sql语句输出到 终端
3、使用
使用 @DS
切换数据源, 该注解 可以跟 类 也可以跟 方法。
- 使用 主库
package com.wtt.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtt.dao.UsersDao;
import com.wtt.pojo.Users;
import com.wtt.service.UsersService;
import org.springframework.stereotype.Service;
@Service
@DS("master")
public class UsersServiceImpl extends ServiceImpl<UsersDao, Users> implements UsersService {
}
- 使用从库
package com.wtt.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtt.dao.NoticeDao;
import com.wtt.pojo.Notice;
import com.wtt.service.NoticeService;
import org.springframework.stereotype.Service;
@Service
@DS("slave_1")
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, Notice> implements NoticeService {
}