MyBatis-Plus
1.简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。同类框架:JPA、tk-mapper、MyBatisPlus。
官方文档地址:https://baomidou.com/
特性:
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
2.快速入门
2.1 建立数据表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
2.2 新建SpringBoot项目
建pom:
添加pom依赖,注意:引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis-plus,里面包含mybatis-->
<!--这个starter是mybatis-plus自己开发的,并非官方的-->
<!--版本不要选新版,新版省略了一些功能,这个版本能看到一些原生的开发-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
写properties
# mysql 5
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mysql 8
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
mapper接口
- 在对应的mapper上面继承基本的类 BaseMapper
- 添加注解@Repository或者@Mapper表示是持久层
- 所有的CRUD操作都已经编写完成了
- 不需要像以前那样配置一大堆文件了
/**
* 在对应的mapper上面继承基本的类 BaseMapper
* 添加注解@Repository或者@Mapper表示是持久层
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
//所有的CRUD操作都已经编写完成了
//不需要像以前那样配置一大堆文件了
}
注意点: 要扫描mapper下的所有接口
@MapperScan("com.ui.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//查询全部用户
//参数是一个wrapper ,条件构造器,这里先不用,null
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
结果
配置日志
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
测试
3.常用操作
3.1 Insert
//测试插入
@Test
void testInsert(){
User user = new User();
user.setName("Java");
user.setAge(3);
user.setEmail("123@qq.com");
int result = userMapper.insert(user);
System.out.println(result);//受影响的行数
System.out.println(user);//发现id会自动添加
}
结果
注意:数据库帮我们生成了id,数据库插入id的默认值为:全局唯一id.
主键生成方式
public enum IdType {
AUTO(0),//数据库id自增
NONE(1),//未设置主键
INPUT(2),//手动输入
ID_WORKER(3),//默认的全局id
UUID(4),//全局唯一的id uuid
ID_WORKER_STR(5);// ID_WORKER的字符串表示法
}
测试自增
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
我们需要配置主键自增:
-
1.实体类字段上增加@TableId(type = IdType.AUTO)
-
2.数据库字段一定要是自增的
测试结果
@Test
void testInsert(){
User user = new User();
user.setName("Java1");
user.setAge(13);
user.setEmail("123@qq.com");
int result = userMapper.insert(user);
System.out.println(result);//受影响的行数
System.out.println(user);//发现id会自动添加
}
3.1.1 补充:主键生成策略
- 数据库自增长序列或字段
- UUID
- UUID的变种
- Redis生成ID
- Twitter的snowflake算法
参考分布式系统唯一ID生成方案汇总
3.2 Update
//测试更新
@Test
void testUpdate(){
//通过条件自动拼接sql
User user = new User();
user.setId(5L);
user.setName("Java");
userMapper.updateById(user);//注意这里参数是一个对象,不是id
}
3.3 补充:自动填充
- 创建时间、修改时间,这些个操作一般都是自动化完成的。
- 阿里开发手册规定:所有数据库表都要有:gmt_create(创建时间)、gmt_modified(修改时间) 几乎所有的表都要配置上,而且要自动化。
方式一:数据库级别(工作中不允许修改数据库表)
- 1.在表中新增字段 create_time update_time
ALTER TABLE `user`
ADD COLUMN `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `email`,
ADD COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间' AFTER `create_time`;
-
注意:导入 SQL 时出现 Invalid default value for ‘create_time’ 报错解决方法
-
这个错误的主要原因,是因为给了时间字段的列默认值一个 CURRENT_TIMESTAMP 默认值,而这个默认值在低版本的 MySQL 中是不支持的,因此就出现了题目中的这个报错。
-
所以重装 MySQL 数据库,版本选择 5.7 或者 5.7 以上版本,或者将默认值改为null。
-
2.再次测试插入方法,我们需要先把实体类同步
private Date createTime;
private Date updateTime;
- 3.再次更新查看结果即可
方式二:代码级别
- 1、删除数据库的默认值,更新的操作
- 2、实体类的字段属性上需要增加注解
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
- 3.编写处理器来处理这个注解即可
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill...");
//setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill...");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
- 4 、测试插入和更新,观察时间即可
3.4 乐观锁
-
乐观锁:它认为不会出现问题,无论干什么不会去上锁,出现问题,再次更新测试
-
悲观锁:它认为总会出现问题,无论干什么都会上锁,再去操作
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
乐观锁过程:
查询获得版本号 version=1
--A
update user set name ="abc",version = version +1
where id = 2 and version = 1
--B线程抢先完成修改,这是version=2,会导致A修改失败
update user set name ="abc",version = version +1
where id = 2 and version = 1
测试MP的乐观锁插件
- 1.给数据库中增加version字段,默认值为1
- 2.实体类加对应字段
@Version //乐观锁注解
private Integer version;
- 3、注册组件
@Configuration //配置类
@EnableTransactionManagement
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
- 4 测试
//测试乐观锁成功
@Test
public void testOptimisticLocker(){
//1.查询用户信息
User user = userMapper.selectById(1L);
//2.修改用户信息
user.setName("potato");
user.setEmail("1232@126.com");
//3.执行更新操作
userMapper.updateById(user);
}
//测试乐观锁失败
@Test
public void testOptimisticLocker2(){
//线程1.
User user = userMapper.selectById(1L);
user.setName("potato111");
user.setEmail("1232@126.com");
//模拟另一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setName("potato111222");
user2.setEmail("1232@126.com");
userMapper.updateById(user2);
//自旋锁来多次尝试提交
userMapper.updateById(user);//如果没有乐观锁,就会覆盖
}
3.5 查询操作
//测试查询
@Test
void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
//测试批量查询
@Test
void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
//测试条件查询 map(后面用warpper)
@Test
void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
//自定义要查询的条件
map.put("name", "Jack");
map.put("age", "20");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
3.6 分页查询
-
1.原始的 limit 进行分页
-
2.pageHelper 第三方插件
-
3.MP也内置了分页插件
使用:
@Configuration //配置类
@EnableTransactionManagement
@MapperScan("com.potato.mapper") //扫描mapper包 @MapperScan("com.potato.mapper")
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
//设置请求页面大于最大页后操作,true调回到首页,false继续请求,默认false
//paginationInterceptor.setOverflow(false)
//设置最大单页限制数量,默认500条,-1不受限制
//paginationInterceptor.setLimit(500)
//开启count的join优化,只针对部分left join
//默认就够用了,不够再设置
return new PaginationInterceptor();
}
}
测试分页查询
//测试分页查询
@Test
void testPage(){
//参数1:当前页 参数2:页面大小
Page<User> page = new Page<>(1,5);//第1页,每页5个
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());//总数
}
3.7 删除操作
//测试删除
@Test
void testDeleteById(){
userMapper.deleteById(1L);
}
//批量删除
void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1L,2L,3L));
}
//通过map删除
void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Java");
userMapper.deleteByMap(map);
}
3.8 逻辑删除
物理删除:从数据库中直接移除
逻辑删除:在数据中没有移除,而是通过一个变量来让它失效,deleted=0 --> deleted=1
目的: 防止数据的丢失,类似于回收站。
测试:
-
1、在数据表中增加一个deleted字段,默认为0
-
2、实体类中增加属性
@TableLogic //逻辑删除
private Integer deleted;
- 3、配置
//逻辑删除
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
- 4、测试一下删除
//测试逻辑删除
@Test
void testDeleteById1(){
userMapper.deleteById(1L);
}
本质是更新操作。
- 5 测试查询
//测试查询
@Test
void testSelectById(){
User user = userMapper.selectById(2L);
System.out.println(user);
}
- 结果
3.9 性能分析插件
在开发中,会遇到慢sql,慢查询,MP也提供了性能分析插件,如果超过这个时间就停止运行。
作用: 性能分析拦截器,用于输出每条SQL语句及其执行时间。
- 1、导入插件
//SQL执行效率插件
@Bean
@Profile({"dev","test"})// 设置dev test环境开启,保证效率
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(30);//设置sql执行的最大时间,如果超过了就不执行
performanceInterceptor.setFormat(true);//是否格式化
return performanceInterceptor;
}
application.properties 设置开发环境或测试环境
#设置开发环境
spring.profiles.active=dev
- 2、测试查询全部数据
4.条件构造器
写一些复杂的sql就可以使用这个来替代。
- 查询name不为空且邮箱不为空的用户,年龄大于等于12岁
@Test
void contextLoads() {
//查询name不为空且邮箱不为空的用户,年龄大于等于12岁
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
.isNotNull("email")
.ge("age",12); //大于等于
userMapper.selectList(wrapper).forEach(System.out::println);//和刚才用的map对比一下
}
- eq
@Test
void test2(){
//查询名字
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Java");
//查询一个数据,出现多个结果使用List或Map
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
- between
@Test
void test3(){
//查询年龄在20-30岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);//区间
Integer integer = userMapper.selectCount(wrapper);//查询结果数
System.out.println(integer);
}
- 模糊查询
@Test
void test4(){
//左和右 %e%
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);//查询结果数
maps.forEach(System.out::println);
}
- 子查询
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//id在子查询中查询出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);//查询结果数
objects.forEach(System.out::println);
}
- 排序
//排序
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通过id进行排序
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
5. 代码生成器
- 新建SpringBoot项目
2.建pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ui</groupId>
<artifactId>auto</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auto</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.写application.properties
# mysql 5
spring.datasource.username=root
spring.datasource.password=110120
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
#设置开发环境
spring.profiles.active=dev
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.代码生成器
@Test
void contextLoads() {
//构建一个代码生成器
AutoGenerator mpg = new AutoGenerator();
//1.全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath);
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("yinan");
gc.setOpen(false);//是否打开输出目录,默认true
gc.setFileOverride(false);//是否覆盖已有文件,默认false
gc.setServiceName("%sService");//service命名方式,去Service的I前缀。默认值:null 例如:%sBusiness 生成 UserBusiness
gc.setIdType(IdType.ASSIGN_ID);//全局唯一id,采用雪花算法。默认:null
gc.setDateType(DateType.ONLY_DATE);//设置日期类型:只显示日期,默认TIME_PACK
// gc.setSwagger2(true);//实体属性 Swagger2 注解,默认false
mpg.setGlobalConfig(gc);
//2.设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("110120");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3.包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.ui");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4.策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");//设置要映射的表名(数据库中的表,可以一次写多个表)
strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);//自动lombok
strategy.setRestControllerStyle(true);//RestController
strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段,对应数据库表的字段deleted
strategy.setControllerMappingHyphenStyle(true);//localhost:8080/hello_id_2
//自动填充配置
TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);//创建时间
TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);//修改时间
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
//乐观锁
strategy.setVersionFieldName("version");
mpg.setStrategy(strategy);
mpg.execute();//执行
}
5.生成结果
6.主启动类上加注解扫描mapper包
@MapperScan("com.ui.blog.mapper")
5.1 Service CRUD 接口
- IService<M,T> 针对业务逻辑层的封装 需要指定Dao层类和对应的实体类 是在BaseMapper基础上的加强
- ServiceImpl 针对业务逻辑层的实现
- 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆
- 泛型 T 为任意实体对象建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
- 对象 Wrapper 为 条件构造器
- 用法:server层接口去继承IService接口,在server层的实现类中去实现方法
6 新版代码生成器使用
pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
@Test
void test(){
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath); //获取当前目录
DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder("jdbc:postgresql://localhost:5432/PatientDB", "root", "999")
.dbQuery(new PostgreSqlQuery())
.typeConvert(new PostgreSqlTypeConvert())
.keyWordsHandler(new PostgreSqlKeyWordsHandler())
.build();
GlobalConfig globalConfig = new GlobalConfig.Builder()
.fileOverride()
.outputDir(projectPath + "/src/main/java")
.author("yinan")
.dateType(DateType.TIME_PACK)
.commentDate("yyyy-MM-dd")
.build();
PackageConfig packageConfig = new PackageConfig.Builder()
.parent("com.ui")
.moduleName("sys")
.entity("do")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.controller("controller")
.other("other")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "/src/main/resources/mapper"))
.build();
StrategyConfig strategyConfig = new StrategyConfig.Builder()
.addTablePrefix("rtc_")
.entityBuilder()
.superClass(BaseDO.class)
.disableSerialVersionUID()
// .enableChainModel()
.enableLombok()
.enableRemoveIsPrefix()
// .enableTableFieldAnnotation()
//.enableActiveRecord()
// .versionColumnName("version")
// .versionPropertyName("version")
// .logicDeleteColumnName("deleted")
// .logicDeletePropertyName("deleteFlag")
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
// .addSuperEntityColumns("id", "creation_time", "creator_user_id", "last_modification_time", "last_modifier_user_id")
// .addIgnoreColumns("age")
// .addTableFills(new Column("create_time", FieldFill.INSERT))
// .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
.idType(IdType.AUTO)
.formatFileName("%sDO")
.build();
AutoGenerator generator = new AutoGenerator(dataSourceConfig);
generator.strategy(strategyConfig);
generator.global(globalConfig);
generator.packageInfo(packageConfig);
generator.execute();
}
}
详细注释看官网:https://baomidou.com/pages/981406/