• mybatis-plus(mp)使用


    1.1 介绍

    MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。–单表操作的都不需要自己在写sql语句。–

    愿景

    我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

    1.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.3 使用

    https://baomidou.com/pages/226c21/#%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96

    (1)创建一个springboot项目

    在这里插入图片描述
    在这里插入图片描述

    (2)创建数据库和表

    /*
     Navicat Premium Data Transfer
    
     Source Server         : Michinaish
     Source Server Type    : MySQL
     Source Server Version : 80011
     Source Host           : localhost:3306
     Source Schema         : mp
    
     Target Server Type    : MySQL
     Target Server Version : 80011
     File Encoding         : 65001
    
     Date: 28/07/2022 10:36:14
    */
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for tbl_user
    -- ----------------------------
    DROP TABLE IF EXISTS `tbl_user`;
    CREATE TABLE `tbl_user`  (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '姓名',
      `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
      `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
      `isdeleted` tinyint(255) UNSIGNED NULL DEFAULT NULL COMMENT '0未删除 1 删除',
      `gmt_created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
      `gmt_modify` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
      `did` int(11) NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of tbl_user
    -- ----------------------------
    INSERT INTO `tbl_user` VALUES (1, 'Jone', 18, 'test1@baomidou.com', 0, NULL, NULL, 1);
    INSERT INTO `tbl_user` VALUES (2, 'ldh', 20, 'test2@baomidou.com', 0, NULL, '2022-07-26 09:19:27', 1);
    INSERT INTO `tbl_user` VALUES (3, 'Tom', 28, 'test3@baomidou.com', 1, NULL, NULL, 1);
    INSERT INTO `tbl_user` VALUES (4, 'Sandy', 21, 'test4@baomidou.com', 0, NULL, NULL, 2);
    INSERT INTO `tbl_user` VALUES (5, 'Billie', 24, 'test5@baomidou.com', 0, NULL, NULL, 3);
    INSERT INTO `tbl_user` VALUES (6, 'zs', 18, '1101@qq.com', 0, NULL, NULL, 2);
    INSERT INTO `tbl_user` VALUES (7, 'ls', 18, '1101@qq.com', 0, '2022-07-26 09:11:27', NULL, 2);
    INSERT INTO `tbl_user` VALUES (8, 'ww', 18, '1101@qq.com', 0, '2022-07-26 09:12:26', '2022-07-26 10:43:18', 3);
    INSERT INTO `tbl_user` VALUES (9, 'zl', 18, '1101@qq.com', 1, '2022-07-26 09:14:35', NULL, 3);
    INSERT INTO `tbl_user` VALUES (12, 'qq', 18, '1121@qq.com', NULL, '2022-07-26 10:39:00', NULL, 1);
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    (3)添加mp依赖
    我是用druid连接池 还需要添加这个依赖

    	<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
    		
    	<dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.2.8</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (4)连接数据库
    在 application.properties 配置文件中编辑数据库连接

    spring.datasource.druid.url=jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai
    spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.druid.username=root
    spring.datasource.druid.password=root
    #初始化的个数
    spring.datasource.druid.initial-size=5
    # 最大活跃数
    spring.datasource.druid.max-active=10
    # 最大等待时间
    spring.datasource.druid.max-wait=3000
    # 最小的闲置个数
    spring.datasource.druid.min-idle=5
    
    #指定映射文件的路径
    mybatis.mapper-locations=classpath:mapper/*.xml
    #日志
    mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    (5)创建实体类

    @Data
    @TableName(value = "tbl_user")
    public class User {
    
        @TableId(value = "id")
        private Integer id;
        private String name;
        private Integer age;
        private String email;
    
        //创建时间
        @TableField(value = "gmt_created")
        private LocalDateTime createTime;
    
        //修改时间
        @TableField(value = "gmt_modify")
        private LocalDateTime modifyTime;
        
        //逻辑删除
        @TableField(value = "isdeleted")
        private Integer isDel;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    (6)创建dao层 继承mp自带的baseMapper

    BaseMapper接口中提供了单表的所有操作。crud.
    
    • 1
    @Mapper //@Mapper是mybatis自身带的注解。在spring程序中,mybatis需要找到对应的mapper,在编译时生成动态代理类,与数据库进行交互,这时需要用到@Mapper注解
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3

    (7)单元测试

    @Autowired
        private UserMapper userMapper;
        @Test
        void contextLoads() {
            System.out.println(userMapper.selectById(1));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    1.4 mp完成crud

    1.4.1添加操作
      主键提供相应的生成策略:
       	AUTO:递增策略,如果使用该策略必须要求数据表的列也是递增。
     	NONE
     	INPUT:没有策略,必须人为的输入id值
      	ASSIGN_ID:
      		随机生成一个Long类型的值,该值一定是唯一,而且每次生成都不会相同。
      		注意:如果实体类中id使用integer则会装不下,数据库中会显示该主键为负数,
      			 所以只需要将实体类的integer 改为long即可
      		算法:雪花算法。
      	 	适合分布式主键。
        ASSIGN_UUID: 随机产生一个String类型的值。该值也是唯一的。
    
    	一般使用主键自增策略 即 auto
    	 @TableId(value = "id",type = IdType.AUTO)
    	 private Integer id;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    测试:

     @Test
        void test01() {
            User user = new User();
            user.setName("dd");
            user.setAge(19);
            user.setEmail("110@qq.com");
            userMapper.insert(user);
            System.out.println("添加后的===="+user); //mp会自动将生成的主键复制给对象 比mybatis好用
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述
    在这里插入图片描述

    1.4.2 删除操作
     实际开发中: 删除可能是逻辑删除,所谓的逻辑删除就是修改功能。把某个列修改以删除的状态值。
     该方式只对自动注入的 sql 起效:
              插入: 不作限制---
              查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
              更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
             删除: 转变为 更新
        操作步骤:
      		(1)增加一个逻辑字段: isdeleted  0表示未删除 1表示删除.
     	    (2)实体类上的字段添加   @TableLogic.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (1)在实体类上添加 @TableLogic.

     //逻辑删除
        @TableField(value = "isdeleted")
        @TableLogic
        private Integer isDel;
    
    • 1
    • 2
    • 3
    • 4

    (2)在配置文件添加默认0表示未删除 1表示删除

    #逻辑删除 1表示删除 0表示未删除
    mybatis-plus.global-config.db-config.logic-delete-value=1
    mybatis-plus.global-config.db-config.logic-not-delete-value=0
    
    • 1
    • 2
    • 3

    (3)测试

    @Test
        void test02() {
            int delete = userMapper.deleteById(1);
            System.out.println(delete);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    1.4.3 修改操作
     自动填充功能:
       在阿里规则中我们的每一张表必须具备的三个字段 id,create_time,update_time.
       这两个字段要不要自己添加。
    
      (1)在需要自动填充属性上@TableField(fill=)
      (2)创建mp自动填充类
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    (1)在创建时间和修改时间属性上添加注解

     //创建时间 表示创建时候会自动填充该时间
        @TableField(value = "gmt_created",fill = FieldFill.INSERT)
        private LocalDateTime createTime;
    
        //修改时间 修改时候会自动修改该时间
        @TableField(value = "gmt_modify",fill = FieldFill.UPDATE)
        private LocalDateTime modifyTime;
    
        //逻辑删除  在做添加时 刚开始删除逻辑应该默认值为0
        @TableField(value = "isdeleted",fill = FieldFill.INSERT)
        @TableLogic
        private Integer isDel;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (2)创建配置类

    	该配置类在我们做添加、删除、修改时可自动修改我们所需的字段
    
    • 1
    @Slf4j
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
    
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill ....");
            //做添加操作的时候 执行自动填充添加时间的值
            this.strictInsertFill(metaObject, "gmtCreated", LocalDateTime.class, LocalDateTime.now());
            //做添加操作的时候 执行自动填充逻辑删除的值
            this.strictInsertFill(metaObject, "isdeleted", Integer.class, 0);
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill ....");
            //做修改操作的时候 执行自动填充修改时间的值
            this.strictUpdateFill(metaObject, "gmtModify", LocalDateTime.class, LocalDateTime.now());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    ①添加操作 自动填充isDel(数据库为字段isdeleted)为0 创建时间自动是当前时间

     @Test
        void test01() {
            User user = new User();
            user.setName("cc");
            user.setAge(19);
            user.setEmail("110@qq.com");
            userMapper.insert(user);
            System.out.println("添加后的===="+user); //mp会自动将生成的主键复制给对象 比mybatis好用
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述
    ②修改操作

    @Test
        void test03() {
            User user = new User();
            user.setName("pp");
            user.setId(16);
            userMapper.updateById(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    这里修改 相当于动态sql 仅仅需要你想修改的字段即可 (打印sql语句如下)

     Preparing: UPDATE tbl_user SET name=?, gmt_modify=? WHERE id=? AND isdeleted=0
     Parameters: pp(String), 2022-07-28T21:23:51.105(LocalDateTime), 16(Integer)  Updates: 1 
    
    • 1
    • 2

    在这里插入图片描述

    1.4.4 查询操作
    Wrapper:条件构造抽象类
    AbstractWrapper:用于查询条件封装,生成sql语句的where条件
    QueryWrapper:Entity 对象封装操作类,不是用lambda语法
    UpdateWrapper:Update条件封装,用于Entity对象更新操作
    AbstractLambdaWrapper:使用Wrapper统一处理解析lambda获取column
    LambdaQueryWrapper :用Lambda语法使用的查询Wrapper
    LambdaUpdateWrapper : Lambda 更新封装Wrapper
    
    有三个子类最常用: 
    QueryWrapper查询条件 
     UpdateWrapper修改条件  
    LambdaQueryWrapper查询使用lambda表达式条件
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    1.4.4.1 根据各种条件查询
        @Test
        void test04() {
            //Wrapper:封装了关于查询的各种条件方法。有三个子类最常用: QueryWrapper查询条件  UpdateWrapper修改条件  LambdaQueryWrapper查询使用lambda表达式条件
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            //查询年龄在15-25之间
            wrapper.between("age",15,25);
            //仅仅查询字段name和age
            wrapper.select("name","age");
            //模糊查询 name中含有a
            wrapper.like("name","l");
            List<User> users = userMapper.selectList(wrapper);
            for (User user:users) {
                System.out.println(user);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    1.4.4.1根据条件查询一条记录
     @Test
        void test05() {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("name","ldh");
            User user = userMapper.selectOne(wrapper);
            System.out.println(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述
    注意:所有的查询经过加了自动注入的删除字段后,每次查询的时候条件都会加上isdeleted=0 所以数据库存在的数据不会全部都查询到。

    常用方法
    	.ge >=,gt >,le <=,lt <(column,val)
    	.eq 等于 (column,val)
    	.ne 不等于(column,val)
    	.between 范围  (column,val1,val2)
    	.like 模糊查询(column,val)
    	.likeLeft likeRight
    	.last (string)用于拼接到sql语句的末端
    	wrapper.select(col1,col2...)选取需要输出的字段
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.5 分页查询

    mp内嵌了分页插件 所以我们可以直接只用 仅仅需要写一个配置类即可

    步骤:
       (1)添加分页拦截器
       (2)调用分页方法
    
    • 1
    • 2
    • 3
    @Configuration
    public class MybatisPlusConfig {
    
        /**
         * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
        @Test
        void test06() {
            Page<User> page = new Page<>(1,3);
            userMapper.selectPage(page,null);把查询的结果自动封装到Page对象中
            System.out.println(page.getPages());//总页码
            System.out.println(page.getTotal());//总条数
            System.out.println(page.getRecords());//当前记录
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在这里插入图片描述

    1.6 联表查询

    因为mp仅仅是对单表操作,所以联表查询还是需要我们手写sql语句

    (1)创建一个部门表

    /*
     Navicat Premium Data Transfer
    
     Source Server         : Michinaish
     Source Server Type    : MySQL
     Source Server Version : 80011
     Source Host           : localhost:3306
     Source Schema         : mp
    
     Target Server Type    : MySQL
     Target Server Version : 80011
     File Encoding         : 65001
    
     Date: 29/07/2022 09:55:06
    */
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for tbl_dept
    -- ----------------------------
    DROP TABLE IF EXISTS `tbl_dept`;
    CREATE TABLE `tbl_dept`  (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `deptname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of tbl_dept
    -- ----------------------------
    INSERT INTO `tbl_dept` VALUES (1, '研发部');
    INSERT INTO `tbl_dept` VALUES (2, '市场部');
    INSERT INTO `tbl_dept` VALUES (3, '财务部');
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    (2)在mapper层书写sql语句 这里使用单元测试 就先不写服务层和业务层

    @Mapper //@Mapper是mybatis自身带的注解。在spring程序中,mybatis需要找到对应的mapper,在编译时生成动态代理类,与数据库进行交互,这时需要用到@Mapper注解
    public interface UserMapper extends BaseMapper<User> {
        IPage<User> selectUserAndDept(IPage<User> page, @Param("ew") Wrapper<User> wrapper);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (3)创建dept实体类

    @Data
    public class Dept implements Serializable {
    
        @TableId(value = "id", type = IdType.AUTO)
        private Integer id;
        private String deptname;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ==注意:==在user实体类中添加dept属性

    private Dept dept;
    
    • 1

    (4)在resources文件下创建mapper层并书写sql语句

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.wx.dao.UserMapper">
        <resultMap id="baseMaper" type="com.wx.entity.User" autoMapping="true">
            <id property="id" column="id"/>
            <association property="dept" javaType="com.wx.entity.Dept" autoMapping="true">
                <id column="did" property="id"/>
            </association>
        </resultMap>
        <select id="selectUserAndDept" resultMap="baseMaper">
            select * from tbl_user u join tbl_dept d on u.did=d.id  where isdeleted=0
            <if test="ew!=null">
                and ${ew.sqlSegment}
            </if>
        </select>
    </mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    (5)测试

     @Test
        void test07(){
            IPage<User> page=new Page<>(1,3);
            Wrapper<User> wrapper=new QueryWrapper<>();
            IPage<User> users=userMapper.selectUserAndDept(page,null);
            System.out.println(users);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    1.7 代码生成器

    1.7.1旧的代码生成器

    public class CodeGenerator {
    
        /**
         * 

    * 读取控制台内容 *

    */
    public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("./src/main/java"); gc.setAuthor("wx"); gc.setOpen(false); gc.setSwagger2(true); //实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("system"); pc.setParent("com.wx"); 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 "./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.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // 写于父类中的公共字段 strategy.setControllerMappingHyphenStyle(true); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103

    1.7.2 新的代码生成器

    public class GeneCode {
        public static void main(String[] args) {
            //数据库配置
            String url="jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai";
            //要自动生成的表名 多个表之间使用逗号隔开
            String[] tables = {"tbl_user","tbl_dept"};
            //获取本项目的路径
            String projectPath = System.getProperty("user.dir");
            //包项目路径
            String outputDir =projectPath+"/src/main/java";
            //xml文件路径
            String outputDirMapper = projectPath+"/src/main/resources/mapper";
            //快速创建
            FastAutoGenerator.create(url, "root", "root")
                    .globalConfig(builder -> {
                        builder.author("wx") // 设置作者
                                .enableSwagger() // 开启 swagger 模式注意 如果要开启swagger 还需要引入swagger注解 否则 可以注释掉这个
                                .fileOverride() // 覆盖已生成文件
                                .outputDir(outputDir); // 指定输出目录
                    })
                    .packageConfig(builder -> {
                        builder.parent("com.wx") // 设置父包名
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, outputDirMapper)); // 设置mapperXml生成路径
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude(tables) // 设置需要生成的表名
                                .addTablePrefix("tbl_"); // 设置过滤表前缀,多个前缀可用逗号隔开
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                    .execute();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    学生HTML网页作业:基于HTML+CSS+JavaScript画家企业8页
    荧光染料BDP FL DBCO,BDP FL 二苯基环辛炔,CAS:2360493-46-3
    原型设计模式
    固体或粘性液体,取决于分子量,FMOC-PEG-COOH,芴甲氧羰基-聚乙二醇-羧基,acid-PEG-FMOC,取用一定要干燥,避免频繁的溶解和冻干
    中国ui设计师年终工作总结
    Matlab图像处理-区域描述
    Vue--组件数据传递与组件切换
    el-form内容重置(解决点击保存关闭后再点击新增会有编辑携带的数据的问题)
    阿里架构师吐血整理:从源码到架构的Spring全系列笔记,已全部分享
    C++笔记梳理
  • 原文地址:https://blog.csdn.net/weixin_44720982/article/details/126029387