文章目录

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1、依赖
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
2、配置文件
配置 MySQL 数据库的相关配置及Mybatis-Plus日志
application.yml
spring:
application:
name: service-oa
profiles:
active: dev
application-dev.yml
server:
port: 8800
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 查看日志
global-config:
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/guigu-oa?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8
username: root
password: 12345
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
3、启动类
在 Spring Boot 启动类中添加
@MapperScan
注解,扫描 Mapper 文件夹
package com.atguigu;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@ComponentScan("com.atguigu")
@MapperScan("com.atguigu.*.mapper")
public class ServiceAuthApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceAuthApplication.class, args);
}
}
4、实体类
package com.atguigu.model.system;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.atguigu.model.base.BaseEntity;
import lombok.Data;
@Data
@TableName("sys_role")
public class SysRole extends BaseEntity {
private static final long serialVersionUID = 1L;
//角色名称
@TableField("role_name")
private String roleName;
//角色编码
@TableField("role_code")
private String roleCode;
//描述
@TableField("description")
private String description;
}
@Data
public class BaseEntity implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@TableField("create_time")
private Date createTime;
@TableField("update_time")
private Date updateTime;
@TableLogic //逻辑删除
@TableField("is_deleted")
private Integer isDeleted;
@TableField(exist = false)
private Map<String,Object> param = new HashMap<>();
}
5、Mapper
com.baomidou.mybatisplus.core.mapper.BaseMapper这是Mybatis-Plus提供的默认Mapper接口
package com.atguigu.auth.mapper;
import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
6、主键策略
6.1、ID_WORKER
MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID
6.2、自增策略
要想主键自增需要配置如下主键策略
- 需要在创建数据表的时候设置主键自增
- 实体字段中配置 @TableId(type = IdType.AUTO)
@TableId(type = IdType.AUTO)
private Long id;
其它主键策略:分析 IdType 源码可知
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/**
* 全局唯一ID
*/
ASSIGN_ID(3),
/**
* 全局唯一ID (UUID)
*/
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
6.3、CURD测试
int result = sysRoleMapper.insert(sysRole);
System.out.println(result); //影响的行数
System.out.println(sysRole); //id自动回填
int result = sysRoleMapper.updateById(sysRole);
System.out.println(result);
/**
* application-dev.yml 加入配置
* 此为默认值,如果你的默认值和mp默认的一样,则不需要该配置
* mybatis-plus:
* global-config:
* db-config:
* logic-delete-value: 1
* logic-not-delete-value: 0
*/
int result = sysRoleMapper.deleteById(2L);
System.out.println(result);
int result = sysRoleMapper.deleteBatchIds(Arrays.asList(1, 1));
System.out.println(result);
7、条件构造器
LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRole::getRoleCode, "role");
List<SysRole> users = sysRoleMapper.selectList(queryWrapper);
System.out.println(users);
8、MyBatis-Plus封装service层
8.1、添加service接口
com.baomidou.mybatisplus.extension.service.IService这是Mybatis-Plus提供的默认Service接口
package com.atguigu.auth.service;
import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
public interface SysRoleService extends IService<SysRole> {
}
8.2、添加service接口实现
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl这是Mybatis-Plus提供的默认Service接口实现
package com.atguigu.auth.service.impl;
import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
}
8.3、测试service接口
//UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper
//所以不填写就是无任何条件
List<SysRole> users = sysRoleService.list();
users.forEach(System.out::println);
boolean result = sysRoleService.save(sysRole);
System.out.println(result); //影响的行数
System.out.println(sysRole); //id自动回填
boolean result = sysRoleService.updateById(sysRole);
System.out.println(result);
boolean result = sysRoleService.removeById(2L);
System.out.println(result);
LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.ge(SysRole::getRoleCode, "role");
List<SysRole> users = sysRoleService.list(queryWrapper);
System.out.println(users);
9、分页插件
9.1、配置分页插件
我们将@MapperScan(“com.atguigu.auth.mapper”)提取到该配置类上面,统一管理,启动类和yaml配置文件就不需要了
package com.atguigu.common.config.mp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.atguigu.auth.mapper")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
9.2、分页controller
//条件分页查询
//page 当前页 limit 每页显示记录数
//SysRoleQueryVo 条件对象
@ApiOperation("条件分页查询")
@GetMapping("{page}/{limit}")
public Result pageQueryRole(@PathVariable Long page,
@PathVariable Long limit,
SysRoleQueryVo sysRoleQueryVo) {
//调用service的方法实现
//1 创建Page对象,传递分页相关参数
//page 当前页 limit 每页显示记录数
Page<SysRole> pageParam = new Page<>(page,limit);
//2 封装条件,判断条件是否为空,不为空进行封装
LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
String roleName = sysRoleQueryVo.getRoleName();
if(!StringUtils.isEmpty(roleName)) {
//封装 like模糊查询
wrapper.like(SysRole::getRoleName,roleName);
}
//3 调用方法实现
IPage<SysRole> pageModel = sysRoleService.page(pageParam, wrapper);
return Result.ok(pageModel);
}
9.3、配置日期时间格式
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8