mybatis-plus增删改查基本操作,简化开发总结
这里只是总结一些个人觉得好用的特性
一.准备工作
拉取依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/数据库名字?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
logging:
level:
com.itxh: debug
pattern:
dateformat: HH:mm:ss
#mybatis:
# mapper-locations: classpath*:mapper/*.xml
mybatis-plus:
type-aliases-package: com.itxh.mp.domain.po
global-config:
db-config:
id-type: auto
logic-delete-field: deleted # 配置逻辑删除字段
configuration:
default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler
knife4j:
enable: true
openapi:
title:
description: ""
email:
concat:小辉
url: https://www.itcast.cn
version: v1.0.0
group:
default:
group-name: default
api-rule: package
api-rule-resources:
- com.itxh.mp.controller
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
@MapperScan("com.itxh.mp.mapper")
@SpringBootApplication
public class MpDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MpDemoApplication.class, args);
}
}
以上是使用此框架的基本操作
之后就是编码实现阶段
这里不再赘述某些配置
在后面会有所提及重要配置yml
二.特性讲解
1.常用注解
为了使得实体类相关属性和数据库表相对应
2.基本使用流程
此处引入黑马教程图
这里的配置是常见的配置,但是有好多都有默认值,还有一些选择性开关,基本操作配个包别名就基本够用,还有一些高级配置会在后面讲到。
还有一些可以去官网查阅
3.条件构造器
具体每个构造器有哪些方法可以用 . 去察看
基本测试类 稍后会讲业务
自己体会吧
后者区别就是可以使用lambda语法,减少耦合度
官网还有好多
其实这些参数都是基本和你写的myabatis里面的mapper.xml里面对应的
比如update
4.自定义sql
基本思路
简单的用注解也能实现
5.mp实现业务准备
6.复杂业务操作
lambda简化
@ApiOperation("扣减用户余额接口")
@PutMapping("/{id}/deduction/{money}")
public void deductBalance(
@ApiParam("用户id") @PathVariable("id") Long id,
@ApiParam("扣减的金额") @PathVariable("money") Integer money){
userService.deductBalance(id, money);
}
void deductBalance(Long id, Integer money);
@Override
@Transactional
public void deductBalance(Long id, Integer money) {
// 1.查询用户
User user = getById(id);//直接调用自己的方法 省的mapper
// 2.校验用户状态
if (user == null || user.getStatus() == UserStatus.FROZEN) {
throw new RuntimeException("用户状态异常!");
}
// 3.校验余额是否充足
if (user.getBalance() < money) {
throw new RuntimeException("用户余额不足!");
}
// 4.扣减余额 update tb_user set balance = balance - ?
int remainBalance = user.getBalance() - money;
lambdaUpdate()
.set(User::getBalance, remainBalance)
.set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
.eq(User::getId, id)
.eq(User::getBalance, user.getBalance()) // 乐观锁 并发
.update();
}
@ApiOperation("根据复杂条件查询用户接口")
@GetMapping("/list")
public List<UserVO> queryUsers(UserQuery query){
// 1.查询用户PO
List<User> users = userService.queryUsers(
query.getName(), query.getStatus(), query.getMinBalance(), query.getMaxBalance());
// 2.把PO拷贝到VO
return BeanUtil.copyToList(users, UserVO.class);
}
List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance);
@Override
public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
return lambdaQuery()
.like(name != null, User::getUsername, name)
.eq(status != null, User::getStatus, status)
.ge(minBalance != null, User::getBalance, minBalance)
.le(maxBalance != null, User::getBalance, maxBalance)
.list();
}
特别好处就是可以加条件
7.批处理
加配置
性能提升
代码生成器
好用的插件自己体会吧,主要好看
8.db静态工具
作用
避免多表联查循环依赖出现,虽说可以解决,但是没必要
唯一区别就是要传入实体类,也是这个实现好的效果
这样就可以不用注入了
@Override
public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
// 1.查询用户
List<User> users = listByIds(ids);
if (CollUtil.isEmpty(users)) {
return Collections.emptyList();
}
// 2.查询地址
// 2.1.获取用户id集合
List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
// 2.2.根据用户id查询地址
List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
// 2.3.转换地址VO
List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
// 2.4.用户地址集合分组处理,相同用户的放入一个集合(组)中
Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
if(CollUtil.isNotEmpty(addressVOList)) {
addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
}
// 3.转换VO返回
List<UserVO> list = new ArrayList<>(users.size());
for (User user : users) {
// 3.1.转换User的PO为VO
UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
list.add(vo);
// 3.2.转换地址VO
vo.setAddresses(addressMap.get(user.getId()));
}
return list;
}
9.逻辑删除
仔细看
10.枚举处理器
只说一种
两部加两个注解
第一个和数据库对应
第二个是要让用户看到的字段
11.json处理器
使用与上面那个一样
12.分页插件
其他操作已经讲过,这里不讲了
13.乐观锁
1.配置类
2.
示例:
// Spring Boot 方式
@Configuration
@MapperScan("按需修改")
public class MybatisPlusConfig {
/**
* 新版
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
这样就很简单的实现了
要是世界也这么简单就好了
这书mybatis作者说的
mp更加简单了
其他功能读者可以自行查阅官网