当前位置: 首页 > news >正文

MyBatis-Plus高效开发实战

概述

MyBatis-Plus 是 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,简化开发、提高效率。本文将介绍 MyBatis-Plus 的几个核心功能在实际项目中的应用

条件构造器

MyBatis-Plus 提供了强大的条件构造器 Wrapper,可以方便地构建复杂的查询条件。如下:

基本查询

// 查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("username", "a").between("age", 20, 30).isNotNull("email");
List<User> list = userMapper.selectList(queryWrapper);

排序查询

// 按年龄降序查询用户,如果年龄相同则按id升序排列
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age").orderByAsc("id");
List<User> users = userMapper.selectList(queryWrapper);

Lambda 表达式

使用 Lambda 表达式可以避免字段名的硬编码,提高代码的可读性和安全性

LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.isNotBlank(username), User::getName, username).ge(ageBegin != null, User::getAge, ageBegin).le(ageEnd != null, User::getAge, ageEnd);

@TableName 注解

@TableName 注解用于指定实体类对应的数据库表名。如下:

@Data
@TableName("product")
public class Product {private Long id;private String name;private Integer price;@Versionprivate Integer version;
}

如果没有使用 @TableName 注解,MyBatis-Plus 会默认使用类名小写形式作为表名

Condition 条件判断

MyBatis-Plus 的条件构造器支持条件判断,可以根据参数是否为 null 来决定是否添加该条件

@Test
public void test08() {String username = null;Integer ageBegin = 10;Integer ageEnd = 24;QueryWrapper<User> queryWrapper = new QueryWrapper<>();if(StringUtils.isNotBlank(username)){queryWrapper.like("username","a");}if(ageBegin != null){queryWrapper.ge("age", ageBegin);}if(ageEnd != null){queryWrapper.le("age", ageEnd);}List<User> users = userMapper.selectList(queryWrapper);
}

更简洁的写法是使用 Lambda 表达式:

LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.isNotBlank(username), User::getName, username).ge(ageBegin != null, User::getAge, ageBegin).le(ageEnd != null, User::getAge, ageEnd);

乐观锁实现

乐观锁是解决并发问题的一种有效方式。MyBatis-Plus 通过 @Version 注解实现乐观锁功能

配置乐观锁插件

在 config 包下配置乐观锁插件:

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;
}

实体类添加版本号字段

在实体类中添加版本号字段(@Version):

@Data
public class Product {private Long id;private String name;private Integer price;@Versionprivate Integer version;
}

乐观锁测试

@Test
public void testConcurrentVersionUpdate() {// 小李取数据Product p1 = productMapper.selectById(1L);// 小王取数据Product p2 = productMapper.selectById(1L);// 小李修改 + 50p1.setPrice(p1.getPrice() + 50);int result1 = productMapper.updateById(p1);// 小王修改 - 30p2.setPrice(p2.getPrice() - 30);int result2 = productMapper.updateById(p2);if (result2 == 0) {// 失败重试,重新获取version并更新p2 = productMapper.selectById(1L);p2.setPrice(p2.getPrice() - 30);result2 = productMapper.updateById(p2);}
}

代码生成器

MyBatis-Plus 提供了代码生成器,可以快速生成 Entity、Mapper、Service、Controller 等代码:

FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&userSSL=false", "root", "123456").globalConfig(builder -> {builder.author("qcby").fileOverride().outputDir("D://mybatis_plus");}).packageConfig(builder -> {builder.parent("com.qcby").moduleName("mybatisplus").pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus"));}).strategyConfig(builder -> {builder.addInclude("t_user").addTablePrefix("t_", "c_");}).templateEngine(new FreemarkerTemplateEngine()).execute();

多数据源配置

MyBatis-Plus 结合 dynamic-datasource 可以轻松实现多数据源配置

数据源配置

在 application.yml 中配置多个数据源

spring:datasource:dynamic:primary: masterstrict: falsedatasource:master:url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSourceusername: rootpassword: 123456slave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSourceusername: rootpassword: 123456

服务层指定数据源

在服务实现类上使用 @DS 注解指定数据源

@DS("master")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}@DS("slave_1")
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}

多数据源测试

@Test
public void testDynamicDataSource(){System.out.println(userService.getById(1L));  // 使用master数据源System.out.println(productService.getById(1L));  // 使用slave_1数据源
}
http://www.lryc.cn/news/601644.html

相关文章:

  • 关于GRPC的相关知识。
  • 编程语言Java——核心技术篇(五)IO流:数据洪流中的航道设计
  • 点击劫持:潜藏在指尖的安全陷阱
  • 【Unity3D实例-功能-移动】角色移动-通过WSAD(Transform方式)
  • 《频率之光:共振之恋》
  • 益莱储:明智地投资测试仪器
  • 数据结构的基本知识
  • [STM32][HAL]stm32wbxx 超声波测距模块实现(HY-SRF05)
  • 深度学习在计算机视觉中的应用:对象检测
  • Java面试全栈通关:从微服务到AI的技术深度解析
  • 市电有电检测电路
  • elasticsearch 倒排索引原理详解
  • 湖南(源点咨询)市场调研 如何在行业研究中快速有效介入 起头篇
  • 一场关于电商零售增长破局的深圳探索
  • Python类(class)参数self的理解
  • ROS2总结(二)
  • VMware Workstation Pro虚拟机的下载和安装图文保姆级教程(附下载链接)
  • Mysql 二进制安装常见问题
  • QUARTUS速通流程
  • HCIP---MGRE实验
  • 数学建模——模糊综合评价
  • 2-4、Dify案例实践—基于工作流构建商城用户评价智能分析系统
  • 算法竞赛阶段二-数据结构(37)数据结构循环链表模拟实现
  • print(“\033[31m红\033[32m绿\033[34m蓝\033[0m默认色“)
  • 零基础学习性能测试第五章:JVM性能分析与调优-JVM运行时内存区域介绍
  • Maven之多模块项目管理
  • C语言——关于指针(逐渐清晰版)
  • 嵌入式——单片机的独立按键
  • 数据结构基础内容(第七篇:堆、哈夫曼树)
  • 电子电气架构 --- 软件bug的管理模式