Mybatis-plus
Mybatis-plus pojo注解
@TableName("") //指定表名@TableId("") //指定主键名 value = "指定主键"; type = "主键生成策略"//type : 例 : 雪花算法//如果使用 ATUO , 确保数据库中主键设置自增@TableField("") //指定列名@TableLogic //指定为逻辑删除列表@EnumValue //放在enum类中 指定数据@Version //乐观锁, 指定为该数据为乐观锁列@DS("") //指定数据源 , 多数据源使用, 在impl上使用, 也可以写在方法上
Mybatis-plus application
mybatis-plus:configuration:#设置myabtis日志类型log-impl: org.apache.ibatis.logging.stdout.StdOutImpl#设置mybatis-plus的全局配置global-config:db-config:#设置实体类所对应的表的统一前缀table-prefix: t_#设置统一的主键生成策略id-type: assign_id
Mybatis-plus 构造器
Wapper 构造器
- Wrapper : 条件构造抽象类, 最顶端父类
- AbstractWrapper : 用于查询条件封装, 生成 sql 的 where 条件
- QueryWrapper : 查询条件封装
- UpdateWrapper : Update 条件封装
- AbstractLambdaWrapper : 使用Lambda语法
- LambdaQueryWrapper : 用于Lambda语法使用的查询Wrapper
- LambdaUpdateWrapper : Lambda 更新封装Wrapper
- AbstractWrapper : 用于查询条件封装, 生成 sql 的 where 条件
构造器是链式编程 Query是非常贴合SQL语法的
//示例@Testpublic void test01(){//查询用户名包含a, 年龄在20到30之间, 邮箱信息不为null的用户信息//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("user_name", "a").between("age", 20, 30).isNotNull("email");List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}
插件
MyBatis-Plus自带分页插件, 只要简单的配置即可实现分页功能
分页
MyBatisPlus分页配置
@Configuration@MapperScan("com.xiao.mybatisplus.mapper")public class MyBatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
/*** 通过年龄查询用户信息并分页* @param page mybatisPlus 所提供的分页对象, 必须位于第一个参数* @param age* @return*/Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
//插件方法Page<User> userPage = new Page<>(page,size);Page<User> users = userMapper.selectPageVo(userPage, 20);System.out.println("内容:"+users.getRecords());System.out.println("总页数"+users.getPages());System.out.println("总条数"+users.getTotal());System.out.println("是否有下一页"+users.hasNext());System.out.println("是否有上一页"+users.hasPrevious());
乐观锁和悲观锁
概念: 在每次修改表时, version列会加1 , 修改一次加一次
详情: https://baomidou.com/pages/0d93c0/#_1-配置插件
SpringBoot配置
@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;}
在实体类的字段上加上@Version注解乐观锁
@Versionprivate Integer version;
通用枚举
mybatis-plus:#扫描通用枚举type-enums-package: com/xiao/mybatisplus/enums
@Getterpublic enum SexEnum {MALE(1,"男"),FEMALE(2,"女");@EnumValue //将注解所标识的属性的值储存到数据库中private Integer sex;private String sexName;SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;}}
代码生成器
注: 不好用
详细: https://baomidou.com/pages/779a6e/#使用
- 引入依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>
- 快速生成 直接Run
public static void main(String[] args) {FastAutoGenerator.create("url", "username", "password").globalConfig(builder -> {builder.author("baomidou") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir("D://"); // 指定输出目录}).packageConfig(builder -> {builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名.moduleName("system") // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://")); // 设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_simple") // 设置需要生成的表名.addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();}
多数据源
适用场景: 纯粹多库, 读写分离, 一主多从, 混合模式等
场景说明: 我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将 mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例 分别获取用户数据与商品数据,如果获取到说明多库模拟成功
引入依赖
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency>
配置多数据源
spring:# 配置数据源信息datasource:dynamic:# 设置默认的数据源或者数据源组,默认值即为masterprimary: master# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源strict: falsedatasource:master:url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456slave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456
指定数据源
@DS("master") //指定所操作的数据源@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper, User> implementsUserService {}
MybatisX插件
代码生成: idea 连接 数据源, 右键数据库, 快速生成crud
代码提示: 在mapper接口 输入方法名, 快速impl生成xml语法 (yyds)
