查看原文
其他

MyBatis-Plus利器

树莓蛋黄派 Java规途 2023-07-04


  • 一、MyBatis-plus概述

    • 1.什么是MyBatis?

    • 2.特性

  • 二、快速入门

    • 1. 快速开始

    • 2. 配置日志

  • 三、增删改查扩展

    • (一)Insert插入

    • (二)主键生成策略

    • (三)更新操作

    • (四)自动填充

    • (五)乐观锁

    • (六)查询操作

    • (七)分页查询

    • (八)删除操作

    • (九)逻辑删除

  • 四、性能分析插件

  • 五、条件构造器

  • 六、代码自动生成器

  • 往期内容


MyBatis-plus

一、MyBatis-plus概述

1.什么是MyBatis-plus?

MyBatis-plus可以帮助我们节省大量时间,所有的增删改查代码都可以自动化完成。

官网网址:MyBatis-plus官网

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 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、快速入门

1. 快速开始

快速开始地址:MyBatis-plus

使用第三方组件

  1. 导入对应的依赖
  2. 研究依赖如何配置
  3. 代码如何编写
  4. 提高技术扩展能力
  • 创建数据库mybatis-plus及User表并添加相应的数据
CREATE DATABASE MyBatis_plus;
USE MyBatis_plus;

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20NOT NULL COMMENT '主键ID',
    name VARCHAR(30NULL DEFAULT NULL COMMENT '姓名',
    age INT(11NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);


INSERT INTO user (idname, 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');

在实际的开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified是必不可少的

  • 初始化项目

使用SpringBoot进行初始化

  • 导入相关的依赖
  <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <!--实体类-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <!--mybatis-plus自己开发,并非官方的-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

mybatis-plus可以节省大量的代码,尽量不要同时导入mybatis和mybatis-plus

  • 连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/MyBatis_plus?userSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

使用了mybatis-plus之后:POJO ->mapper接口 -> 使用

  • POJO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

}

  • Mapper接口
@Repository
public interface UserMapper extends BaseMapper<User> {
    //mybatis-plus需要在此基础上继承BaseMapper
    //所有的增删改查操作全部编写完成

}

需要继承BaseMapper,继承其所有的增删改查方法,并且可以依据自身需要完成方法的扩展,

同时需要注意我们需要在主启动类上去添加@MapperScan(“包的全路径”)去扫描对应的包下的所有mapper接口

@MapperScan("com.example.dao")
@SpringBootApplication
public class MybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }

}
  • 使用
class MybatisPlusApplicationTests {
    @Autowired
    private UserMapper userMapper;
    //继承了BaseMapper父类所有的增删改查方法,
    // 我们也可以编写自己的扩展方法

    @Test
    void contextLoads() {

        //查询全部用户,参数是一个wrapper,是一个条件构造器,可以设置为null
        List<User> users = userMapper.selectList(null);
        users.forEach(user -> {
            System.out.println(user);
        });

    }

需要注意的是userMapper.selectList(wrapper参数),其中的参数代表的是条件构造器,不需要的时候可以设置为null

2. 配置日志

现在所有的SQL是不可见的,只有看日志才能知道SQL究竟是如何执行的。

此处由于使用LOG4J等其他日志需要另外加入新的依赖,因此,此处使用系统的标准输出日志

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

标准的输出日志如下:

三、增删改查扩展

(一)Insert插入

  //插入测试
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("Mike");
        user.setAge(18);
        user.setEmail("154545454@qq.com");
        int affectRow = userMapper.insert(user); //帮助我们自动生成id
        System.out.println(affectRow);
        System.out.println(user);
    }

最终结果:

mybatis-plus会帮助我们自动生成id

数据库插入的默认值为我们全局的唯一id

(二)主键生成策略

分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html

雪花算法

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。雪花算法支持的TPS可以达到419万左右(2^22*1000)。几乎可以保证全球唯一。

 @TableId(type = IdType.ID_WORKER)
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;
    }
}

  1. 默认ID WORKER

全局唯一ID

  1. 主键自增
   @TableId(type = IdType.AUTO)

配置主键自增策略:

  • 实体类上添加注解@TableId(type = IdType.AUTO)
  • 数据库字段一定要是自增的

测试insert操作

//设置@TableId(type = IdType.AUTO)
@Test
    public void testInsert(){
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setEmail("1544545454@qq.com");
        int affectRow = userMapper.insert(user); 
        System.out.println(affectRow);
        System.out.println(user);
    }

结果如下:

  1. 手动输入
 @TableId(type = IdType.INPUT)
 @Test
    public void testInsert(){
        User user = new User();
        user.setName("李四");
        user.setAge(18);
        user.setEmail("1459563454@qq.com");
        int affectRow = userMapper.insert(user); //帮助我们自动生成id
        System.out.println(affectRow);
        System.out.println(user);
    }

将id变化设置为手动输入,其对应的插入对象的id设置为null

因此,一旦手动输入之后,一定要自己配置对应的id

(三)更新操作

  //测试更新操作
    @Test
    public void testUpdate(){
        User user = new User();
        user.setAge(25);
        user.setId(6L);
        user.setEmail("14597984544@qq.com");
        int i = userMapper.updateById(user);
    }

使用updateById(User t)完成id为6的记录的更改,更改的内容主要有年龄和email

结果如下:

结果是mybatis-plus自动拼接了动态SQL

(四)自动填充

创建时间、修改时间、这些操作一般都是自动化完成的,不希望手动更新。

所有的数据库表都应该包含以下两个字段:gmt_create 、gtm_modified(几乎所有的表都必须要配置上,而且需要自动化更新)

  1. 数据库级别自动填充-不建议使用

在表中新增字段gmt_create 、gtm_modified

ALTER TABLE User ADD create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT'创建时间';

ALTER TABLE User ADD update_time  datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_STAMP COMMENT '更新时间'

再次测试插入方法并同步实体类

 private Date createTime;
 private Date updateTime;
  @Test
    public void testUpdate(){
        User user = new User();
        user.setAge(17);
        user.setId(6L);
        user.setEmail("145974544@qq.com");
        int i = userMapper.updateById(user);
    }

结果更新了更新时间

  1. 代码级别自动填充
  • 删除数据库级别的默认操作
  • 实体类字段属性上增加注解(@TableField)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableField {
    String value() default "";

    String el() default "";

    boolean exist() default true;

    String condition() default "";

    String update() default "";

    FieldStrategy strategy() default FieldStrategy.DEFAULT;

    FieldFill fill() default FieldFill.DEFAULT;

    boolean select() default true;
}

  /**为以下两个属性设置相应的注解*/
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

创建字段需要在插入的时候进行更新,更新字段需要在插入和更新的时候都进行相应的更新操作。

  • 编写处理器处理注解

需要实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler

@Slf4j
@Component /**需要将相应的组件添加至IOC容器中*/
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**插入时候的填充策略*/
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert start.......");
        //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("update start......");
        //更新时间在更新的时候填充
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
}

  • 插入测试
 //插入测试
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("小明");
        user.setAge(16);
        user.setEmail("145936854@qq.com");
        int affectRow = userMapper.insert(user); //帮助我们自动生成id
        System.out.println(affectRow);
        System.out.println(user);
    }

    //测试更新操作
    @Test
    public void testUpdate(){
        User user = new User();
        user.setAge(19);
        user.setId(1502634608783667204L);
        user.setEmail("145974544@qq.com");
        int i = userMapper.updateById(user);
    }

结果是插入数据的时候两个时间点都发生了改变,但是更新的时候,创建时间不变,更新时间发生了变化。

(五)乐观锁

乐观锁:十分乐观,总是认为不会出现问题,不论干什么,都不会上锁,如果出现问题,再次更新测试(version new version)

悲观锁:十分悲观,它总是认为会出现问题,无论干什么,都会先上锁,然后再去进行相应的操作

乐观锁机制

乐观锁实现方式:

  • 取出记录时,获取当前 version
  • 更新时,带上这个 version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果 version 不对,就更新失败
UPDATE user SET name=‘xxx’,version=oldversion+1 WHERE id=2 AND version=oldversion;

如果条件中version=oldversion不成立,则无法完成插入操作,可以保证线程间的安全通信。

乐观锁的实现

  1. 在数据库中添加version字段
ALTER TABLE user ADD version int DEFAULT 1 COMMENT '乐观锁';

此时表中的所有行的version均为1

  1. 实体类添加对应的字段并添加version注解
  /**添加乐观锁字段*/
    @Version
    private Integer version;
  1. 注册乐观锁组件(创建config文件夹并创建类)
/**扫描对应的mapper文件夹*/
@MapperScan("com.example.dao")
@EnableTransactionManagement/**自动管理事务*/
@Configuration /**表示这是一个配置类*/
public class MyBatisPlusConfig {

  //注册乐观锁插件
  @Bean
  public OptimisticLockerInterceptor optimisticLockerInterceptor() {
      return new OptimisticLockerInterceptor();
  }
}

  1. 测试
  • 单线程下的乐观锁
  //测试乐观锁成功
    @Test
    public void testOptimisticLock(){
        //查出id为1的用户
        User user = userMapper.selectById(1L);
        //修改用户信息
        user.setName("李白");
        user.setEmail("454645@qq.com");
        //执行更新操作
        int i = userMapper.updateById(user);


    }

此时单线程下可以执行成功。

  • 模拟多线程下的乐观锁
//多线程下测试乐观锁
    @Test
    public void testOptimisticLocker(){
        //线程1
        User user = userMapper.selectById(1L);
        user.setName("李白");
        user.setEmail("454645@qq.com");

        //线程2执行插队操作

        User user1 = userMapper.selectById(1L);
        //修改用户信息
        user1.setName("李白1");
        user1.setEmail("4546451@qq.com");
        //执行更新操作
        int i1 = userMapper.updateById(user1);


        //如果没有乐观锁就会覆盖插队线程的值
        //要想实现原先的操作,需要使用自旋锁尝试提交
        int i = userMapper.updateById(user);

    }

如果线程2插队提交了修改,那么线程1将无法再对数据库完成操作,因为version的值已经发生了改变。

如果想要被插队的线程执行成功,可以设置自旋锁完成相应的重复提交操作。

(六)查询操作

 //测试查询
    @Test
    public void testQuery(){
        User user = userMapper.selectById(1);
        System.out.println(user);

    }

    //查询多个用户(批量查询)
    @Test
    public void testBatchUser(){
        //此处需要传递的参数为一个Collection类型
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1234));
        //users.forEach(user -> {
        //    System.out.println(user);
        //});
        users.forEach(System.out::println);
    }

    //测试条件查询,使用Map
    @Test
    public void testQueryBy(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","李白");
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

}

基本的查询和条件查询mybatis-plus都可以完成操作

(七)分页查询

分页在网站使用很多。可以使用limit分页、pagehelper分页,mybatis-plus的分页

使用mybatis-plus实现分页

  1. 配置拦截器组件
 //注册分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor(){
      PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
      ////设置请求的页面大于最大页后操作,true调回到首页,false继续请求,默认false
      //  paginationInterceptor.setOverflow(false);
      //  //设置最大单页限制数量,默认500条 -1不受限制
      //  paginationInterceptor.setLimit(500);
      //  //开启count的join优化,只针对部分的left join
      //  paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;

    }
}
  1. 直接使用page对象即可
//方法的API参数
IPage<T> selectPage(IPage<T> var1, @Param("ew") Wrapper<T> var2);
  //测试分页查询
    @Test
    public void testLimitPage(){
        //由于需要page对象,所以需要创建page,参数表示第一页,查询三个数据(1.当前页,2.页面大小)
        Page<User> page = new Page<>(1,3);
        //由于方法参数需要Ipage对象,wrapper:表示高级查询
        userMapper.selectPage(page,null);
        page.getRecords().forEach(System.out::println);
    }

结果如下:

首先在分页查询之前,会进行总页数的查询,上例中总数为6,在总数为6的表中查询条数据,本质上仍旧是使用的Limit来实现分页查询。

使用了分页插件之后,所有的分页操作都变得简单了。

(八)删除操作

  1. 根据id删除对应的数据
  //测试删除数据
    @Test
    public void testDelete(){
        //通过id来删除用户
        int i = userMapper.deleteById(1502634608783667204L);
        if (i>0){
            System.out.println("删除成功!");
        }else {
            System.out.println("删除失败!");
        }
    }
  1. 批量删除相关的数据
  //测试批量删除
    @Test
    public void testBatchDelete(){
        int i = userMapper
                .deleteBatchIds(Arrays.asList(1502634608783667205L,1502634608783667206L,1502634608783667207L));

        if (i>0){
            System.out.println("删除成功!");
        }else {
            System.out.println("删除失败!");
        }
    }

成功实现批量删除相关的内容

  1. 通过map删除数据
  //测试通过Map删除
    @Test
    public void testDeleteByMap(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","小华");
        int i = userMapper.deleteByMap(map);
        if (i>0){
            System.out.println("删除成功!");
        }else {
            System.out.println("删除失败!");
        }
    }

(九)逻辑删除

在工作中常常会遇到的是逻辑删除

  • 物理删除:从数据库中直接移除
  • 逻辑删除:在数据库中没有被移除,通过变量使它失效,比如将原来的delete由0变为1,使其失效

例如网站管理员可以查看被删除的记录,这样做是为了防止数据的丢失,类似于回收站。

  1. 在数据表中增加一个deleted字段
ALTER TABLE user ADD deleted int DEFAULT 0 COMMENT '逻辑删除';
  1. 实体类中增加属性
 /**添加逻辑删除属性与逻辑删除注解*/
    @TableLogic//逻辑删除注解
    private Integer deleted;

  1. 配置相关的逻辑删除(注册逻辑删除组件)
    //注册逻辑删除组件
  @Bean
  public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
  }
  1. 配置逻辑删除
# 配置逻辑删除(没有删除的值为0,删除的设置为1)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
  1. 测试删除用户
  @Test
    public void testDelete(){
        //通过id来删除用户
        int i = userMapper.deleteById(1502634608783667209L);

        if (i>0){
            System.out.println("删除成功!");
        }else {
            System.out.println("删除失败!");
        }
    }

结果如下

记录依旧在数据库,deleted的值发生了变化。

进行逻辑删除之后,再次查询该用户,会自动过滤被逻辑删除的字段

四、性能分析插件

平时的开发中,会遇到一些慢sql。mybatis-plus也提供了性能分析插件,如果超过这个时间就会停止运行。

作用:性能分析插件,用于输出每条SQL语句及其执行的时间。

性能分析插件的使用:

  1. 配置插件
 //SQL的执行效率插件
  @Bean
  @Profile({"dev","test"})// 只是在测试和开发环境下使用,提高效率。
  public PerformanceInterceptor performanceInterceptor(){
    //获取性能分析拦截器对象
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    //可以设置sql执行的最大时间,如果超过了则不执行。ms
    performanceInterceptor.setMaxTime(1);
    //开启格式化支持true
    performanceInterceptor.setFormat(true);

    return performanceInterceptor;
  }

其中可以设置sql执行的最大时间以及是否开启格式化支持

  1. 配置sql执行环境

将其设置为测试环境或者开发环境。

# 设置开发环境
spring.profiles.active=dev
  1. 测试查询
    @Test
    void contextLoads() {

        //查询全部用户,参数是一个wrapper,是一个条件构造器,可以设置为null
        List<User> users = userMapper.selectList(null);
        users.forEach(user -> {
            System.out.println(user);
        });

    }

结果如下:

对sql进行了相应的格式化操作

由于超时,导致相应的查询操作不能够顺利执行,时间超时(原本设置为1ms)

使用性能分析插件,我们可以提高效率

五、条件构造器

wrapper:十分重要,条件构造器

我们写一些复杂的sql,就可以使用wrapper来进行替代。

  1. 测试一:查询年龄大于12,并且名字与邮箱不为空的用户

使用isNotNullge方法

   @Test
    void contextLoads() {
        //查询name不为空的用户(复杂查询)并且邮箱不为空的用户,年龄大于12岁的
        //由于查询需要使用到warpper
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //可以使用链式编程
        wrapper.isNotNull("name")
                .isNotNull("email")
                .ge("age",12);
        //查询参数为wrapper
        List<User> users =
                userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }
  1. 测试二:测试eq方法
  @Test
    void test2(){
        //需要查询名字为小煌的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //查询条件名字为小煌的
        wrapper.eq("name","Jack");
        //查询一个用户使用selectOne,出现多个结果使用map或者list
        System.out.println(userMapper.selectOne(wrapper));


    }
  1. 测试三:查询某个区间的用户

使用between()方法,其中selectCount表示查询的结果数

   @Test
    public void test3(){
        //查询年龄在20-30之间的用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age",20,30);
        //selectCount表示查询结果数
        Integer integer = userMapper.selectCount(wrapper);
        System.out.println("年龄在20-30之间的有:"+integer);
    }
  1. 测试四:使用notLikelikeRight

其中notLike是指不包含的意思,likeRight是指通配符在右边的条件。即邮箱以t开头的所有用户

  @Test
    public void test4(){
        //使用模糊查询,查询名字中
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //左与右:其实代表的是%是在左边还是右边
        //查询名字中不包含e字母的
            wrapper.notLike("name","e")
                    //表示查询email中以t开头的
            .likeRight("email","t");
        List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
        maps.forEach(System.out::println);

    }

测试结果

  1. 测试五:子查询inSql()方法
   @Test
    public 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);
    }

结果:

  1. 测试六:排序

使用orderByDesc进行降序排序,里面传入id

 @Test
    public void test6(){
        //测试通过id进行排序
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //通过id进行降序排序
        wrapper.orderByDesc("id");

        List<User> users = userMapper.selectList(wrapper);

    }

结果如下:根据id进行了降序排序

六、代码自动生成器

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

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

//代码自动生成器
public class AutoCode {
    public static void main(String[] args) {
        //构建一个代码自动生成器对象
        AutoGenerator mpg=new AutoGenerator();

        //执行之前需要配置一些策略
        //1.全局配置
        GlobalConfig gc = new GlobalConfig();
        //获取当前系统目录
        String projectPath = System.getProperty("user.dir");
        //设置代码输出的目录
        gc.setOutputDir(projectPath+"/src/main/java");
        //设置作者
        gc.setAuthor("Lambda");
        //是否打开资源管理器
        gc.setOpen(false);
        //是否覆盖原来生成的
        gc.setFileOverride(false);
        //去掉service的I前缀
        gc.setServiceName("%sService");
        //设置id生成策略
        gc.setIdType(IdType.ID_WORKER);
        //设置日期类型
        gc.setDateType(DateType.ONLY_DATE);
        //设置swagger
        gc.setSwagger2(true);

        mpg.setGlobalConfig(gc);

        //2. 设置数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/MyBatis_plus?userSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setPassword("xielibin20001011");
        //设置数据库的类型
        dataSourceConfig.setDbType(DbType.MYSQL);
        mpg.setDataSource(dataSourceConfig);

        //3.配置一系列的要生成的包
        PackageConfig packageConfig = new PackageConfig();
        //设置模块名
        packageConfig.setModuleName("blog");
        //设置包路径,生成com.example.blog这个模块
        packageConfig.setParent("com.example");
        //设置具体的包名
        packageConfig.setEntity("entity");
        packageConfig.setMapper("mapper");
        packageConfig.setService("service");
        packageConfig.setController("controller");
        mpg.setPackageInfo(packageConfig);

        //4.策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        //设置需要映射的表名
        strategyConfig.setInclude("user");
        //设置下划线转驼峰命名
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        //设置列名格式
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        //设置自身的父类实体,没有就不设置
        strategyConfig.setSuperEntityClass("父类实体,没有就不设置");
        //设置启动Lombok
        strategyConfig.setEntityLombokModel(true);
        //设置restful风格
        strategyConfig.setRestControllerStyle(true);
        //设置逻辑删除的名字
        strategyConfig.setLogicDeleteFieldName("deleted");

        //设置自动填充策略
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        //将上述的策略填充仅tableFills中
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategyConfig.setTableFillList(tableFills);

        //设置乐观锁
        strategyConfig.setVersionFieldName("version");

        //设置url的下划线命名
        strategyConfig.setControllerMappingHyphenStyle(true);

        //将策略设置进mpg生成器对象
        mpg.setStrategy(strategyConfig);
        //执行代码构造
        mpg.execute();

    }

}

当需要生成不同的代码的时候只需要相应得更改 strategyConfig.setInclude("user");表名即可。

往期内容

---JAVA

Java

+=







JAR


Object


IO

XML

Java线JUC

JDBC

Maven

MyBatis

JavaWeb-

IOCAOP>Spring

Apache Ant+Apache Maven>Gradle

SSM

SpringMVC概述


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存