springboot-mybatisplus-代码生成器

1.引入依赖

<dependencies>
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
	
    <!--mysql驱动-->
    <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.22</version>
    </dependency>
	
    <!--druid数据源-->
    <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.2.4</version>
    </dependency>
	
    <!-- mybatis-plus 相关-->
    <dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.4.1</version>
    </dependency>
	
    <!-- 代码生成器 -->
    <dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-generator</artifactId>
     <version>3.4.1</version>
    </dependency>
	
    <!-- 模板引擎 -->
    <dependency>
     <groupId>org.apache.velocity</groupId>
     <artifactId>velocity-engine-core</artifactId>
     <version>2.2</version>
    </dependency>
    <!-- mybatis-plus 结束-->
	
	
    <!--以下是工具包-->
    <dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
     <version>5.5.7</version>
    </dependency>
    <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.75</version>
    </dependency>
    <!-- lombok -->
    <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <version>1.18.12</version>
     <scope>provided</scope>
    </dependency>
	
</dependencies>

2.yml

server:
  port: 8181
  servlet:
    context-path: /sa  # 共有前缀
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/lantoliang?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
      # 连接池配置
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 连接超时时间
      max-wait: 30000
      #配置检监控可以关闭的空闲连接间隔时间
      time-between-eviction-runs-millis: 60000
      # 配置连接在池中的最小生存时间
      min-evictable-idle-time-millis: 300000


3.创建表

CREATE TABLE `user_info` (
  `id` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL COMMENT '用户名',
  `password` varchar(64) NOT NULL COMMENT '密码',
  `sex` char(1) DEFAULT NULL COMMENT '性别 0 女| 1 男',
  `locked` char(1) DEFAULT NULL COMMENT '是否锁住 0 否 | 1 是',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `create_by` varchar(32) DEFAULT NULL COMMENT '创建者',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `update_by` varchar(32) DEFAULT NULL COMMENT '更新者',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4. 公共字段提取到BaseEntity.java

id,创建者,创建时间,修改者,修改时间

@Data
public class BaseEntity {
    /**
     * id 生成策略为UUID
     */ @TableId(type = IdType.ASSIGN_UUID)
    private String id;
     /**
     * 创建者 填充策略为插入自动填充
     */
     @TableField(fill = FieldFill.INSERT)
    private String createBy;
     /**
     * 创建时间 填充策略为插入自动填充
     */
     @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
     /**
     * 更新者 填充策略为更新自动填充
     */
     @TableField(fill = FieldFill.UPDATE)
    private String updateBy;
     /**
     * 更新时间 填充策略为更新自动填充
     */
     @TableField(fill = FieldFill.UPDATE)
    private LocalDateTime updateTime;
}

5.然后新建一个自动填充策略类MpMetaObjectHandler.java

对应4的
插入:创建者,创建时间,
修改:修改者,修改时间

public class MpMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     * @param metaObject
     */
     @Override
     public void insertFill(MetaObject metaObject) {
            // 起始版本 3.3.0(推荐使用)
     this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
     this.strictInsertFill(metaObject, "createBy", String.class, "第二级路径(com.第二级)");
     }
        /**
     * 更新时的填充策略
     * @param metaObject
     */
     @Override
     public void updateFill(MetaObject metaObject) {
	  // 官网原文,如果属性有值或者填充值为null的时候不进行填充,所以这边先手动把需要自动填充的值变成null
        metaObject.setValue("updateTime",null);
        metaObject.setValue("updateBy",null);
            // 起始版本 3.3.0(推荐)
     this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
     this.strictUpdateFill(metaObject, "updateBy", String.class, "第二级路径(com.第二级)");
     }
}

6.新建一个mybatis plus的配置类注入填充策略Bean

包扫描
分页插件
公共字段自动填充策略

@Configuration
public class MybatisPlusConfig {
    /**
     * 相当于顶部的:@MapperScan("com.example.demo.*.dao")
     * {@code @MapperScan("com.example.demo.*.dao")}
     * 这里可以扩展,比如使用配置文件来配置扫描Mapper的路径
     */
     @Bean
     public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
     scannerConfigurer.setBasePackage("com.example.demo.daoo");
     return scannerConfigurer;
     }
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */ @Bean
     public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
     interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
     return interceptor;
     }
    /**
     * 公共字段自动填充策略
     *
     * @return
     */
     @Bean
     public MpMetaObjectHandler mpMetaObjectHandler() {
            return new MpMetaObjectHandler();
     }
}

7.编写代码生成器

package com.example.demo.codeGenerator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.example.demo.entity.BaseEntity;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class CodeGenerator {
    public static void create() throws FileNotFoundException {
        String projectPath = System.getProperty("user.dir");
        // 1、声明代码生成器
        AutoGenerator generator = new AutoGenerator();
        // 2、全局信息配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig
                // 输出目录
                .setOutputDir(projectPath + "/src/main/java")
                // 是否覆盖原有文件 默认false
                .setFileOverride(false)
                // 是否打开输出目录 默认true
                .setOpen(false)
                // 作者
                .setAuthor("lantoliang")
                // 设置实体类名称
                .setEntityName("%s")
                // 设置mapper 命名方式
                .setMapperName("%sDao")
                // Mapper xml 命名方式
                .setXmlName("%sDao")
                //service 命名方式
                .setServiceName("%sService")
                //service impl 命名方式
                .setServiceImplName("%sServiceImpl")
                //controller 命名方式
                .setControllerName("%sController")
                // Mapper xml 生成基础 查询列 可以不设置
                .setBaseColumnList(true)
                //Mapper xml 生成基础返回map 可以不设置
                .setBaseResultMap(true)
                .setSwagger2(true);
        // 3、数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        // 设置数据库类型和数据源
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setDriverName("com.mysql.cj.jdbc.Driver")
                .setUrl("jdbc:mysql://localhost:3306/lantoliang?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8")
                .setUsername("root")
                .setPassword("root");
        // 4、策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                // 数据库表映射实体 下划线转大写,驼峰命名方式
                .setNaming(NamingStrategy.underline_to_camel)
                // 数据库字段映射实体属性 下划线转大写,驼峰命名方式
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setLogicDeleteFieldName("deleted")
                // 生成 @RestController 控制器
                .setRestControllerStyle(true)
                // 设置controller继承的父类
                // .setSuperControllerClass(BaseController.class)
                // entity继承的父类
                .setSuperEntityClass(BaseEntity.class)
                // entity继承类的字段
                .setSuperEntityColumns("id", "create_by", "create_time", "update_by", "update_time")
                // 是否生成lombok模式
                .setEntityLombokModel(true)
                //要生成的表名
                .setInclude("user_info"); // 目前是只有一个表,多个用,隔开
        // 设置表前缀,生成的实体名称不包含前缀
        //        if (StrUtil.isNotEmpty() {
        //            strategyConfig.setTablePrefix();
        //        }
        // 5、生成代码包信息配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig
                // 设置生成的包名的父类名称
                .setParent("com.example.demo")
                .setController("controller")
                .setEntity("entity")
                .setMapper("dao")
                .setService("service")
                .setServiceImpl("service.impl");
        //xml 自定义输出到java 文件夹下,所以下面自定义输出路径
        //                .setXml(mapper");
        // 6、自定义要注入到模板的属性
        InjectionConfig injectionConfig = new InjectionConfig() {
            // 必须实现的方法, 内容可以放空
            @Override
            public void initMap() {
                //                Map<String, Object> map = new HashMap<>(4);
                //                map.put("moduleName", "");
                //                map.put("description", "");
                //                this.setMap(map);
            }
        };
        List<FileOutConfig> fileOutConfigList = new ArrayList<>();
        FileOutConfig fileOutConfig = new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML;
            }
        };
        fileOutConfigList.add(fileOutConfig);
        injectionConfig.setFileOutConfigList(fileOutConfigList);
        // 7 自定义模板~~~~
        TemplateConfig templateConfig = new TemplateConfig();
        // xml自定义输出路径,所以设置为null
        templateConfig.setXml(null);
        // 8、整合配置
        generator.setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setTemplate(templateConfig)
                .setCfg(injectionConfig);
        //9、执行
        generator.execute();
    }
    
}

8. 测试

public static void main(String[] args) throws FileNotFoundException {
        CodeGenerator.create();
    }

问题反馈

Mybatis plus 分页查询 left join 子查询参数无法找到报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LC超人在良家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值