1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 尚硅谷MyBatis-Plus学习笔记

尚硅谷MyBatis-Plus学习笔记

时间:2023-02-03 23:21:04

相关推荐

尚硅谷MyBatis-Plus学习笔记

1.MyBatis-Plus

目录

1.MyBatis-Plus1.1特性1.2支持数据库1.3框架结构 2.MP快速上手2.1导入依赖2.2修改配置2.2.1单源2.2.2多源 2.3注解使用2.4条件构造器使用2.4.1分页使用2.4.2查询2.4.2.1selectMaps2.4.2.2动态查询 3.MP基本内容3.1配置application.yml3.2Mapper接口✳3.3加入日志功能3.4测试自定义功能3.5Service接口✳3.6@TableName注解3.7@TableId注解3.7.1Value属性3.7.2Type属性 3.8雪花算法3.9@TableFild注解3.10@TableLogic注解 4.MP条件构造器✳4.1Wapper介绍4.2QuerryWrapper4.2.1组装查询4.2.2组装排序4.2.3组装删除4.2.4组装修改4.2.5条件的优先级(条件优先级查询)4.2.6组装select字句(排除某些字段查询)4.2.7组装字查询4.2.8动态查询✳ 4.3UpdateWrapper4.4LambdaQueWrapper4.5LambdaUpdateWrapper 5.MP**分页**插件✳5.1常规分页5.2自定义分页 6.MP乐观锁和悲观锁6.1乐观锁插件6.2悲观锁插件 7.MP通用枚举@EnumValue8.MP代码生成器9.MP配置多数据源10.MyBatisX插件11.知识加油站11.1lombok

1.1特性

无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

1.2支持数据库

任何能使用MyBatis进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库,优炫数据库

1.3框架结构

2.MP快速上手

官网地址:/pages/24112f/

2.1导入依赖

pom.xml

<!--MyBatisPlus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency>

2.2修改配置

application.yml

2.2.1单源

#mybatis-plusmybatis-plus:#配置类型别名所对应的包type-aliases-package: com.example.domain#设置mybatis-Plus的统全局配置global-config:db-config:#设置实体类对应的统一前缀table-prefix: tb_# 生成统一的主键生成策略id-type: autoconfiguration:# 打印Mybatis-plus的执行日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

type-aliases-package: com.example.domain

2.2.2多源

spring:datasource:dynamic:#设置默认的数据源或者数据源组,默认值即为masterprimary: master #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源strict: false datasource:master:url: jdbc:mysql://xx.xx.xx.xx:3306/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置mysql2:url: jdbc:mysql://xx.xx.xx.xx:3307/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermysql2:url: ENC(xxxxx) # 内置加密,使用请查看详细文档username: ENC(xxxxx)password: ENC(xxxxx)driver-class-name: com.mysql.cj.jdbc.Driver#......省略

2.3注解使用

@Service、@Mapper、@TableName、@TableId、@TableFild、@TableLogic、@EnumValue、@DS

@Service

public interface IBookService extends IService<Book> {}

@Servicepublic class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {}

实现接口,继承Service

如果多源:

@DS("master")@Servicepublic class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {}

需要使用@DS注解使用源

@Mapper

@Mapperpublic interface BookDao extends BaseMapper<Book> {}

继承实体类

@TableName

//设置实体类对应的表名@TableName("t_user")public class Book {}

若在yml文件中进行了配置,此步骤可省略

@TableId

public class Book {//将属性对应的字段作为主键//@TableId注解的value属性用于指定主键的字段//@TableId注解的type属性设置主键生成策略@TableId(value = "uid", type = IdType.AUTO)//private Integer id;private Integer uid;}

设置数据库对应主键ID

@TableFild

@Datapublic class Book {private String type;//指定属性所对应的字段名@TableField("book_name")private String name;}

设置对应数据库的字段名

@TableLogic

@Datapublic class Book {//设置属性是否逻辑删除@TableLogicprivate int isDelete;}

是否逻辑删除

需要添加数据库字段

@EnumValue

@Getterpublic enum SexEnum {MALE(1, "男"),FEMALE(2, "女");;//将注解所标识的属性的值存储到数据库中@EnumValueprivate Integer sex;private String sexName;SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;}}

使用枚举存入值

2.4条件构造器使用

2.4.1分页使用

若需要使用mp的分页工则需要添加配置类

@Configurationpublic class MpConfig {@Beanpublic MybatisPlusInterceptor mInterceptor() {//1.定义Mp拦截器MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();//2.添加具体的拦截器(添加分页拦截器,实现分页查询的动态SQL)mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return mpInterceptor;}}

@Testpublic void testPage(){Page<User> page = new Page<>( current: 2,size: 3);userMapper.selectPage(page,queryWrapper: null);system.out.println(page);}

2.4.2查询

2.4.2.1selectMaps

@Testpublic void test06(){//查询用户的用户名、年龄、邮箱信息Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.select( "user_name", "age","email" );List<Map<String,object>> maps = userMapper.selectMaps(querywrapper);maps.forEach(system.out: :println);}

2.4.2.2动态查询

public void test10(){string username = "a";Integer ageBegin = null;Integer ageEnd = 30;Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.like(stringutils.isNotBLank(username),column: "user_name", username).ge( condition: ageBegin != null,column: "age", ageBegin).le( condition: ageEnd l= null,column: "age", ageEnd);List<user> list = userMapper.selectList(querywrapper);list.forEach(system.out : :println);}

加个条件判断

3.MP基本内容

3.1配置application.yml

spring:# 设置数据源datasource:# 设置驱动类driver-class-name: com.mysql.cj.jdbc.Driver#配置连接数据库的各个信息url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTCusername: rootpassword: qweasdzxc

流程:

设置数据源设置驱动类配置连接数据库的各个信息

注意

MySQL5.7版本的url:

jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&usesSL=false

MySQL8.0版本的url:

jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false

否则运行测试用例报告如下错误:

java.sql.SQLException: The server time zone value ‘OD1uzé×E士14a’ is unrecognized or representsmore

3.2Mapper接口✳

@Mapperpublic interface BookDao extends BaseMapper<Book> {}

使用@Mapper注解。在IOC容器中只能存在类所存在的Bean,不能存在接口所存在的Bean。因此将动态生成的代理类交给了IOC容器管理

@Mapeper将当前接口标为持久层,并为Springboot所管理

3.3加入日志功能

mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

加入日志功能,可打印出相关的sql语句。注意:sql语句的生成是mybatis-plus将实体类对应的泛型反射为SQL语句。

例如,BaseMapper此处的Book,就为实体类

3.4测试自定义功能

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.BookDao"><!--定义接口方法对应的 SQL 语句--></mapper>

3.5Service接口✳

public interface IBookService extends IService<Book> {}

IService T为泛型,填写对象

@Servicepublic class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {}

ServiceImpl<BookDao, Book> M为Mapper,T为泛型

3.6@TableName注解

//设置实体类对应的表名@TableName("t_user")@Datapublic class Book {private Integer id;private String type;private String name;private String description;}

同时,我们也可以在yml文件中对表的前缀进行统一处理

#mybatis-plusmybatis-plus:#设置mybatis-Plus的统全局配置global-config:db-config:#设置实体类对应的统一前缀table-prefix: tb_

3.7@TableId注解

@Datapublic class Book {//将属性对应的字段作为主键@TableId// private Integer id;private Integer uid;private String type;private String name;private String description;}

mybatis-plus会将表中的属性作为数据库中的字段名

当数据库的表中的主键id没有设置为默认自增长时,而实体类的唯一标识为“ uid”(而不是“id”),那么MyBatis-Plus就不能通过反射实体类的属性来找到表中字段的唯一标识,就需要通过注解来指明

3.7.1Value属性

@Datapublic class Book {//将属性对应的字段作为主键//@TableId注解的value属性用于指定主键的字段@TableId("uid")private Integer id;private String type;private String name;private String description;}

当数据库中的字段名与实体类的类名对应不上时进行使用。vaule默认可以省略

3.7.2Type属性

@Datapublic class Book {//将属性对应的字段作为主键//@TableId注解的value属性用于指定主键的字段//@TableId注解的type属性设置主键生成策略@TableId(value = "uid", type = IdType.AUTO)private Integer id;private String type;private String name;private String description;}

常用的主键策略

ldType.ASSIGN_ID(默认):基于雪花算法的策略生成数据id,与数据库id是否设置自增无关

ldType.AUTO:使用数据库的自增策略,注意,该类型请确保数据库设置了id自增,否则无效

#mybatis-plusmybatis-plus:#设置mybatis-Plus的统全局配置global-config:db-config:#设置实体类对应的统一前缀table-prefix: tb_# 生成统一的主键生成策略id-type: autoconfiguration:# 打印Mybatis-plus的执行日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Type属性也可以根据yml文件的 id-type: auto来进行统一生成

3.8雪花算法

背景

需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量。数据库的扩展方式主要包括:业务分库、主从复制,数据库分表。

雪花算法中在分布式中应用非常的广泛,因为雪花算法的有点性

3.9@TableFild注解

@Datapublic class Book {//将属性对应的字段作为主键//@TableId注解的value属性用于指定主键的字段//@TableId注解的type属性设置主键生成策略@TableId(value = "uid", type = IdType.AUTO)private Integer id;private String type;//指定属性所对应的字段名@TableField("book_name")private String name;private String description;}

​ @TableField不是特别的常用,若数据库中的字段名是这样的形式“book_name”那么mybatis-plus会自动的将下划线转换为bookName如此大驼峰的命名方式,反之亦然

3.10@TableLogic注解

物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为"被删除状态”,之后在数据库中仍旧能看到此条数据记录使用场景:可以进行数据恢复

@Datapublic class Book {//将属性对应的字段作为主键//@TableId注解的value属性用于指定主键的字段//@TableId注解的type属性设置主键生成策略@TableId(value = "uid", type = IdType.AUTO)private Integer id;private String type;//指定属性所对应的字段名@TableField("book_name")private String name;private String description;//设置属性是否逻辑删除@TableLogicprivate int isDelete;}

当数据库中的字段有isDelete字段时,给对应的实体类加上此注解。在后续的mybatis-plus的删除功能中,实际会执行sql中的update的修改操作,将isDelete变为1。与此同时,mybatis-plus的查询的操作,实际在执行sal中,自动加上and is_delete = 0的操作,查询出未删除的数据

4.MP条件构造器✳

4.1Wapper介绍

Wrapper:条件构造抽象类,最顶端父类AbstractWrapper : 用于查询条件封装,生成sql 的where条件 QueryWrapper :查询条件封装UpdateWrapper : Update条件封装AbstractLambdaWrapper:使用Lambda语法 LambdaQueryWrapper:用于Lambda语法使用的查询WrapperLambdaUpdateWrapper : Lambda更新封装wrapper

4.2QuerryWrapper

4.2.1组装查询

@Testpublic void testo1(){//查询用户名包含a,年龄在20到3o之间,邮箱信息不为nuLl的用户信息Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.like( "user_name", "a").between( "age", 20, 30).isNotNull( "email");List<user> list = userMapper.selectList(querywrapper);list.forEach(system.out: : println) ;}

注: querywrapper.like中的参数 column是数据库中的字段名,并不是实体类中的属性名

4.2.2组装排序

@Testpublic void test02(){//查询用户信息,按照年龄的降序排序,若年龄相同,则按照id升序排序Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.orderByDesc("age").orderByAsc("uid");List<user> list = userMapper.selectListlquerywrapper);list.forEach(system.out::println);}

注: querywrapper.orderByDesc中的参数 column是数据库中的字段名,并不是实体类中的属性名

4.2.3组装删除

@Testpublic void test03(){//删除邮箱地址为null的用户信息Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.isNull( "email" );int result = userMapper.delete(querywrapper);system.out.print1n("result: "+result); }

注: querywrapper.isNull中的参数 column是数据库中的字段名,并不是实体类中的属性名

4.2.4组装修改

@Testpublic void test04(){//将(年龄大于20并且用户名中包含有a)或邮箱为nuLl的用户信息修改Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.gt( "age", 20).like( "user_name", "a").or().isNul1( "email");user user = new User();user.setName("小明");user.setEmail( "test@" );int result = userMapper.update(user,querywrapper);system.out.println("result: "+result);}

注: querywrapper.gt中的参数 column是数据库中的字段名,并不是实体类中的属性名

gt大于,or或许,like 模糊匹配

4.2.5条件的优先级(条件优先级查询)

Testpublic void test05(){//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改// Lambda中的条件优先执行Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.like( column: "user_name",val: "a").and(i->i.gt( column: "age" , val: 20).or( ).isNull( column: "email"));User user = new User();user.setName("小红");user.setEmail("test@" ) ;int result = userMapper.update(user,querywrapper);system.out.println( "result: "+result);}

注意Lambada表达式优先执行

参考资料:深入浅出 Java 8 Lambda 表达式 - 姚春辉 - 博客园 ()

4.2.6组装select字句(排除某些字段查询)

@Testpublic void test06(){//查询用户的用户名、年龄、邮箱信息Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.select( "user_name", "age","email" );List<Map<String,object>> maps = userMapper.selectMaps(querywrapper);maps.forEach(system.out: :println);}

如果想要查询数据库中的某些值,可用select进行组装

4.2.7组装字查询

public void test07(){//查询id小于等于100的用户信息Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.inSql( column: "uid",inValue: "select uid from t_user where uid <= 100")List<User> list = userMapper.selectList(querywrapper);list.forEach(system.out : :print1n);

嵌套子查询,如需要用到字查询类的值,可使用嵌套子查询进行

4.2.8动态查询✳

public void test10(){string username = "a";Integer ageBegin = null;Integer ageEnd = 30;Querywrapper<User> querywrapper = new Querywrapper<>();querywrapper.like(stringutils.isNotBLank(username),column: "user_name", username).ge( condition: ageBegin != null,column: "age", ageBegin).le( condition: ageEnd l= null,column: "age", ageEnd);List<user> list = userMapper.selectList(querywrapper);list.forEach(system.out : :println);}

当需要使用动态Sql来进行条件拼接时,可使用mp的condition功能

4.3UpdateWrapper

public void testo8(){//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改Updatewrapper<User> updatewrapper = new updatewrapper<>();updatewrapper.like( column: "user_name",val: "a").and(i -> i.gt( column: "age",val: 20).or( ).isNull( column: "email"));updatewrapper.set("user_name","小黑").set("email" , "abc@" );int result = userMapper.update( entity: null,updatewrapper);system.out.println("result: "+resulth);}

修改功能的使用

4.4LambdaQueWrapper

@Testpublic void test11(){string username = "a";Integer ageBegin = null;Integer ageEnd = 30;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);List<User> list = userMapper.selectList(querywrapper);list.forEach(system.out::print1n);}

当使用LambadaQuerapper时,配置参数的第二个参数是与QuerryWrepper不相同的,它是函数式的接口,其中第二个参数可设置为user::getAge,为了防止程序员将查询的名字写错

4.5LambdaUpdateWrapper

@Testpublic void test12(){//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改LambdaUpdatewrapper<User> updatewrapper = new LambdaUpdatewrapper<>();updatewrapper.like(User: :getName,val: "a").and(i -> i.gt(User : :getAge,val: 20).or().isNull(User::getEmail));updatewrapper.set(User::getName,"小黑").set(User::getEmail,"abc@");int result = userMapper.update( entity: null,updatewrapper);System.out.println("result: "+result);}

当使用LambdaUpdateWrapper时,配置参数的第二个参数是与updatewrapper不相同的,它是函数式的接口,其中第二个参数可设置为user::getAge,为了防止程序员将查询的名字写错

跟LambdaQueWrapper类似

5.MP分页插件✳

5.1常规分页

若需要使用mp的分页工则需要添加配置类

@Configurationpublic class MpConfig {@Beanpublic MybatisPlusInterceptor mInterceptor() {//1.定义Mp拦截器MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();//2.添加具体的拦截器(添加分页拦截器,实现分页查询的动态SQL)mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return mpInterceptor;}}

@Testpublic void testPage(){Page<User> page = new Page<>( current: 2,size: 3);userMapper.selectPage(page,queryWrapper: null);system.out.println(page);}

MP分页功能的其余方法

iPage.getPages();iPage.getSize();iPage.getCurrent();iPage.getRecords();iPage.getTotal();

5.2自定义分页

在自定义的sql查询后实现分页功能

UserMapper.java

/***通过年龄查询用户信息并分页*@param page MyBatis-PLus所提供的分页对象,必须位于第一个参数的位訇@param age*@return*/Page<User> selectPagevo(@Param( "page") Page<User> page,@Param("age") Integer age);

application.yml

mybatis-plus:#配置类型别名所对应的包type-aliases-package: com.example.domain#设置mybatis-Plus的统全局配置global-config:db-config:#设置实体类对应的统一前缀table-prefix: tb_ # 生成统一的主键生成策略id-type: autoconfiguration:# 打印Mybatis-plus的执行日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

type-aliases-package: com.example.domain

对应映射文件UserMapper.xml

<select id="selectPagevo" resultType="User">select uid,user_name,age,email from t_user where age > #{age}</select>

返回值类型 设置返回的为User,因为最终是返回为User对象

注意,此处需要在yml文件中进行配置别名

测试

@Testpublic void testPagevo(){Page<User> page = new Page<>( 1, 3);userMapper.selectPagevo(page, 20);system.out.println(page.getRecords());system.out.println(page.getPages());system.out.println(page.getTotal());system.out.println(page.hasNext());system.out.println(page.hasPrevious());}

6.MP乐观锁和悲观锁

6.1乐观锁插件

乐观锁实现流程

数据库中添加version字段取出记录时,获取当前version

SELECT id, 'name`,price, 'version` FROM product WHERE id=1

更新时,version +1,如果where语句中的version版本不对,则更新失败

UPDATE product SET price=price+50,‘version '='version`+ 1 WHERE id=1 AND‘version'=1

1.数据库中添加version字段

2.实体类添加@Version注解

@Datapublic class Book {private Integer id;private String type;private String name;private String description;@Version //标识乐观锁版本号字段private Integer version;}

3.配置类中添加乐观锁拦截器

@Configurationpublic class MpConfig {@Beanpublic MybatisPlusInterceptor mInterceptor() {//1.定义Mp拦截器MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();//2.添加具体的拦截器(添加分页拦截器,实现分页查询的动态SQL)mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//3.添加具体的拦截器(添加乐观锁拦截器,实现乐观锁的查询)mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mpInterceptor;}}

6.2悲观锁插件

一个人在操作时,另一个人不能同时进行操作

7.MP通用枚举@EnumValue

1.假设数据库中存储age字段类型为int(类型不相匹配的字段)

2.枚举类添加@EnumValue注解

@Getterpublic enum SexEnum {MALE(1, "男"),FEMALE(2, "女");;//将注解所标识的属性的值存储到数据库中@EnumValueprivate Integer sex;private String sexName;SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;}}

注意:需要添加@EnumValue来实现数据库的存值,某则会将汉字存入数据库中

@Datapublic class Book {private Integer id;private String type;private String name;private String description;private SexEnum sex;}

补充:在实体类中使用枚举类时,需要将类型设定为枚举类型

3.配置application.yml

#mybatis-plusmybatis-plus: #扫描通用枚举包type-enums-package: com.example.enums

4.使用枚举类型

user.setsex(SexEnum.MALE);

在使用时,需要从枚举类中读取即可

8.MP代码生成器

1.导入依赖 pom.xml

<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>

2.快速生成

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.xml, "D://")); // 设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_simple") // 设置需要生成的表名.addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();

9.MP配置多数据源

1.添加yml配置

application.yml

spring:datasource:dynamic:#设置默认的数据源或者数据源组,默认值即为masterprimary: master #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源strict: false datasource:master:url: jdbc:mysql://xx.xx.xx.xx:3306/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置mysql2:url: jdbc:mysql://xx.xx.xx.xx:3307/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermysql2:url: ENC(xxxxx) # 内置加密,使用请查看详细文档username: ENC(xxxxx)password: ENC(xxxxx)driver-class-name: com.mysql.cj.jdbc.Driver#......省略

2.更改数据源

@DS("master")@Servicepublic class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {}

10.MyBatisX插件

使用方法

1.idea中 DataBase右击构造,快速生成

2.选择module,package,实体类,忽略前缀和表前缀

3.一般如下选择配置

11.知识加油站

11.1lombok

<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>

@Datapublic class Book {private Integer id;private String type;private String name;private String description;}

LomBok不会生成有参构造的方法

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。