MyBatis-Plus(入门学习记录)

(大部分内容源自官方,以及bilibili狂神说)

基本了解

1.介绍

官网地址:mp.baomidou.com/

是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

image-20210529145840633

image-20210529150131775

2.特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

3.支持数据库

任何能使用 mybatis 进行 crud, 并且支持标准 sql 的数据库

4.框架结构

framework

快速开始

步骤

1.创建数据库mybatis_plus

image-20210529150657299

2.创建User表

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)
);
--真实开发中,加入versio(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified
复制代码

3.插入数据

DELETE FROM user;

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');
复制代码

4.创建项目

image-20210529151516495

5.导入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0</version>
    <relativePath/>
</parent>
复制代码

引入 spring-boot-starter、spring-boot-starter-test、mybatis-plus-boot-starter、h2 依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>
复制代码

注意:建议不要同时使用mybatis和mybatis_plus

Asia/Shanghai

useSSL=false&useUnicode=true&characterEncoding=utf-8

6.编写配置

# 应用名称
spring.application.name=mybatis_plus
# 应用服务 WEB 访问端口
server.port=8080

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

复制代码

注意mysql8.0一定要写时区!

7.创建实体类

package com.gip.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private long id;
    private String name;
    private Integer age;
    private String email;
}

复制代码

8.创建接口

package com.gip.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gip.pojo.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends BaseMapper<User> {

}

复制代码

注意:要继承BaseMapper,并传入你要的类型

然后在启动类上门扫码dao包@MapperScan("com.gip.dao"),或者改用@mapper注解

9.测试

package com.gip;

import com.gip.dao.UserDao;
import com.gip.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    UserDao userDao;

    @Test
    void contextLoads() {
        final List<User> users = userDao.selectList(null);
        users.forEach(System.out::println);
    }

}

复制代码

结果:

image-20210529160613882

配置日志

将sql语句打印在控制台上

image-20210529161119926

# 日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
复制代码

使用log4j或者其他第三方日志,要导入相对应的依赖,这里测试,采用默认的

再次运行查看结果

可以看到日志信息

image-20210529161343030

CRUD拓展

1.Insert

 @Test
    public void testInsert() {
        User user = new User();
        user.setName("Gip");
        user.setAge(18);
        user.setEmail("11111@qq.com");
        int insert = userDao.insert(user);
        System.out.println(insert);
        System.out.println(user);
    }
复制代码

image-20210529162248446

image-20210529162301576

id是0

发现问题

将实体类的id属性类型换成Long包装类型,后再次运行测试方法

private Long id;
复制代码

发现自动生成一大串的id

image-20210529162820911

主键生成策略

分布式系统唯一ID生成方案汇总:blog.csdn.net/rainyear/ar…

Twitter的snowflake算法

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看github.com/twitter/sno…

注解@TableId设置主键

默认@TableId(type= IdType.NONE)

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.baomidou.mybatisplus.annotation;

public enum IdType {
    AUTO(0),//数据库id自增,数据库中的表要开启自增
    NONE(1),//未设置主键
    INPUT(2),//手动输入
    ID_WORKER(3),//默认全局唯一id
    UUID(4),//全局唯一id uuid
    ID_WORKER_STR(5);//ID_WORKER 字符串表示法

    private int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}
复制代码

image-20210529165730983

2.Update

@Test
public void testUpdate() {
    User user = new User();
    user.setName("Gip");
    user.setAge(22);
    user.setEmail("11111@qq.com");
    user.setId(6L);
    int i = userDao.updateById(user);
    System.out.println(i);
}
复制代码

image-20210529170854525

观察sql语句,发现其可以自动拼接动态sql

3.自动填充

创建时间、修改时间!这些操作自动化完成

基本上所有表都应该要有gmt_create、gmt_modified字段,来追踪数据的创建时间和修改时间

方式一:数据库级别(工作中不建议使用)

1.在表中新增字段create_time,update_time

image-20210529172648494

update_time添加更新操作

image-20210529172704285

2.修改实体类,使用驼峰命名

    private Date createTime;
    private Date updateTime;

复制代码

运行更新方法

结果:

image-20210529173713913

方式二:代码级别(?)

1.删除数据库默认值,和更新操作

2.实体类字段属性上加入注解@TableField

 	//字段填充内容
    @TableField(fill= FieldFill.INSERT)
    private Date createTime;
    @TableField(fill= FieldFill.INSERT_UPDATE)
    private Date updateTime;
复制代码

3.编写处理器来处理这个注解

创建包com.gip.handler,创建一个MyMetaObjectHandler类要实现MetaObjectHandler接口

package com.gip.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
//注册到IOC容器中
@Component
//开启日志功能
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
    log.info("插入时候处理开始");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新时候处理开始");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

复制代码

4.运行更新操作

image-20210529175735888

嗯完成了

5.运行插入

image-20210529175921433

4.乐观锁

乐观锁:顾名思义,它非常乐观,无论干什么都不去上锁,出现问题,再次更新值测试

悲观锁:十分悲观,无论干什么,都会上锁,再去操作!

OptimisticLockerInnerInterceptor

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

配置:

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

在实体类的字段上加上@Version注解

@Version
private Integer version;
复制代码

说明:

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • update(entity, wrapper) 方法下, wrapper 不能复用!!!

用一下官方新的案例,依赖更新下

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>
复制代码

image-20210530112809464

数据库中加入version字段

@Version
private int version;
复制代码

测试

@Test
public void testLock() {
    User user = userDao.selectById(6);
    System.out.println(user);
    user.setName("Gip2");
    User user2 = userDao.selectById(6);
    user2.setName("Gip3");
    userDao.updateById(user2);
    userDao.updateById(user);
}
复制代码

最终更新的是Gip3,成功上锁image-20210530113805008

5.Select

    //测试查询
    @Test
    public void testSelect() {
        User user = userDao.selectById(6);
        System.out.println(user);
    }
    @Test
    public void testSelects(){
        List<User> users = userDao.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);
    }
}
复制代码

image-20210530114646032

//按条件查询
@Test
public void testSelectMap() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("name", "Gip");
    map.put("age",18);
    List<User> users = userDao.selectByMap(map);
    users.forEach(System.out::println);
}
复制代码

image-20210530142905615

6.分页查询

分页在使用频率很高

1.原始limit分页

2.使用插件PageHelper

3.使用Myatis_Plus内置分页插件

image-20210530150527834

//添加分页功能
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
复制代码

属性介绍

属性名 类型 默认值 描述
overflow boolean false 溢出总页数后是否进行处理(默认不处理,参见 插件#continuePage 方法)
maxLimit Long 单页分页条数限制(默认无限制,参见 插件#handlerLimit 方法)
dbType DbType 数据库类型(根据类型获取应使用的分页方言,参见 插件#findIDialect 方法)
dialect IDialect 方言实现类(参见 插件#findIDialect 方法)

建议单一数据库类型的均设置 dbType

你也可以不设置(测试环境mysql,设置方言mysql)

interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

测试:

//分页测试
@Test
public void testPage() {
    //当前页
    //页面大小
    Page<User> page = new Page<>(1,5);
    userDao.selectPage(page, null);
    page.getRecords().forEach(System.out::println);
}
复制代码

如果返回类型是 IPage 则入参的 IPage 不能为null,因为 返回的IPage == 入参的IPage
如果返回类型是 List 则入参的 IPage 可以为 null(为 null 则不分页),但需要你手动 入参的IPage.setRecords(返回的 List);
如果 xml 需要从 page 里取值,需要 page.属性 获取

其他:

生成 countSql 会在 left join 的表不参与 where 条件的情况下,把 left join 优化掉
所以建议任何带有 left join 的sql,都写标准sql既给于表一个别名,字段也要 别名.字段

所以方法返回值的对象就是你传入的page对象,你可以随便用哪个,反正都是同个

image-20210530151000897

image-20210530150912795

7.Delete

//    删除测试
@Test
public void testDelete() {
    userDao.deleteById(1398579652407803905L);
}

//批量删除
@Test
public void testDeleteByIds() {
    int i = userDao.deleteBatchIds(Arrays.asList(1398566092763967489l, 1398579652407803905L));
}
复制代码

image-20210530153838605

long类型赋值,加上l就行(l和L都行不区分大小写)

image-20210530153921767

删除成功!

//条件删除
@Test
public void testDeleteMap() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("name","Gip");
    userDao.deleteByMap(map);
}
复制代码

image-20210530154133170

image-20210530154140247

8.逻辑删除

物理删除:从数据库中直接移除

逻辑删除:没有真正删除,通过设置标识变量,标识失效

测试:

1.在数据库中加入一个字段deleted

image-20210530154929213

2.在实体类中,添加注解@TableLogic

@TableLogic
private int deleted;
复制代码

说明:

只对自动注入的sql起效:

  • 插入: 不作限制
  • 查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
  • 更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
  • 删除: 转变为 更新

例如:

  • 删除: update user set deleted=1 where id = 1 and deleted=0
  • 查找: select id,name,deleted from user where deleted=0

字段类型支持说明:

  • 支持所有数据类型(推荐使用 Integer,Boolean,LocalDateTime)
  • 如果数据库字段使用datetime,逻辑未删除值和已删除值支持配置为字符串null,另一个值支持配置为函数来获取值如now()

附录:

  • 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
  • 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。

mp.baomidou.com/guide/logic…

application.yml

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
复制代码
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
复制代码

新版本只要加注解@TableLogic就行了,不需要你配置,你想配置也可以,底层原理都是auto注入

测试删除6号用户

image-20210530160257734

发现其执行更新语句,将标识改写

image-20210530160320309

去查6号,ok可以看到他加了deleted字段判断,所以查不出来了

image-20210530160505494

大大提升了程序员写sql的效率!!!mybatis_plus YES

性能分析插件

开发过程中遇到慢sql,需要排查分析,测试,druid,压力测试都可以做这个事情

内置性能分析插件(新版本已经移除,当前版本3.4.3(无)推荐使用外部性能分析插件,然后执行 SQL 分析打印)

mp.baomidou.com/guide/p6spy…

image-20210530161211330

条件构造器

很重要!:Wrapper

复杂SQL使用它解决!

mp.baomidou.com/guide/wrapp…

image-20210530164048009

AbstractWrapper

说明:

QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为

@Test
public void Test1() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .isNotNull("name")
            .isNotNull("email")
            .ge("age", 18);
    userDao.selectList(wrapper).forEach(System.out::println);
}
复制代码

image-20210530174733010

@Test
public void Test2() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //查询一个用户,叫Gip3
    wrapper.eq("name","Gip3");
    System.out.println(userDao.selectOne(wrapper));
}
复制代码

image-20210530175219621

查询范围数据

@Test
public void Test3() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
	 //查询18-22范围
    wrapper.between("age","18","22");
    //查询数量
    Integer count = userDao.selectCount(wrapper);
    System.out.println(count);
}
复制代码

image-20210530175729744

参数我给String,也可以查出来,应该给int类型,不过无所谓,最终都是解析成sql语句是个字符串

搞一下

image-20210530180006037

发现原来不会覆盖,而是继续添加相同条件

image-20210530180040370

试试模糊查询

//模糊查询
@Test
public void Test4() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .notLike("name","G")
            .likeRight("name","J");
    System.out.println(userDao.selectMaps(wrapper));
}
复制代码

结果:%G%(String), J%(String)

Preparing: SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND (name NOT LIKE ? AND name LIKE ?)
==> Parameters: %G%(String), J%(String)
<== Columns: id, name, age, email, create_time, update_time, version, deleted
<== Row: 1, Jone, 18, test1@baomidou.com, null, null, 1, 0
<== Row: 2, Jack, 20, test2@baomidou.com, null, null, 1, 0
<== Total: 2

//内查询
@Test
public void Test5() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //id在内查询中查出来
    wrapper.inSql("id", "select id  from  user where id<3");
    List<Object> objects = userDao.selectObjs(wrapper);
    objects.forEach(System.out::println);

}
复制代码

SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND (id IN (select id from user where id<3))

排序

//排序查询
@Test
public void Test6() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.orderByDesc("id");
    List<Object> objects = userDao.selectObjs(wrapper);
    objects.forEach(System.out::println);
}
复制代码

image-20210530192403996

代码自动生成器

mp.baomidou.com/guide/gener…

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

特别说明:

自定义模板有哪些可用参数?Github (opens new window)AbstractTemplateEngine 类中方法 getObjectMap 返回 objectMap 的所有值都可用。

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("密码");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.baomidou.ant");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享