赞
踩
AutoGenerator 是 MyBatis Plus推出的代码生成器,可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,比Mybatis Generator更强大,开发效率更高。
以往我们使用mybatis generator生成代码正常需要配置mybatis-generator-config.xml,代码配置比较繁琐复杂,比如:
<generatorConfiguration><contextid="myContext"targetRuntime="MyBatis3"defaultModelType="flat"><!-- 注释 --><commentGenerator><!-- 是否不生成注释 --><propertyname="suppressAllComments"value="true"/></commentGenerator><!-- jdbc连接 --><jdbcConnectiondriverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://ip:3306/codingmoretiny02?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false"userId="codingmoretiny02"password="123456"><!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true--><propertyname="nullCatalogMeansCurrent"value="true"/></jdbcConnection><!-- 类型转换 --><javaTypeResolver><propertyname="forceBigDecimals"value="true"/></javaTypeResolver><!-- 生成实体类地址 --><javaModelGeneratortargetPackage="com.codingmore.mbg.po"targetProject="src/main/java"><!-- 是否针对string类型的字段在set方法中进行修剪,默认false --><propertyname="trimStrings"value="true"/></javaModelGenerator><!-- 生成Mapper.xml文件 --><sqlMapGeneratortargetPackage="com.codingmore.mbg.mapper"targetProject="src/main/resources"></sqlMapGenerator><!-- 生成 XxxMapper.java 接口--><javaClientGeneratortargetPackage="com.codingmore.mbg.dao"targetProject="src/main/java"type="XMLMAPPER"></javaClientGenerator><tableschema=""tableName="user"domainObjectName="User"enableCountByExample="false"enableDeleteByExample="false"enableSelectByExample="false"enableUpdateByExample="false"selectByExampleQueryId="false"></table></context></generatorConfiguration>复制代码
- SET NAMES utf8mb4;
- SET FOREIGN_KEY_CHECKS =0;
-
- -- ------------------------------ Table structure for user-- ----------------------------DROPTABLE IF EXISTS `user`;
- CREATETABLE `user` (
- `id` bigint(20) NOTNULL AUTO_INCREMENT,
- `username` varchar(50) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NOTNULL COMMENT '用户名',
- `mobile` varchar(100) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NULLDEFAULTNULL COMMENT '手机号',
- `create_by` varchar(64) CHARACTERSET utf8mb4 COLLATE utf8mb4_general_ci NULLDEFAULTNULL COMMENT '创建人',
- `create_time` datetime(0) NULLDEFAULTNULL COMMENT '创建时间',
- PRIMARY KEY (`id`) USING BTREE,
- UNIQUE INDEX `username`(`username`) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT =2CHARACTERSET= utf8mb4 COLLATE= utf8mb4_general_ci COMMENT ='用户' ROW_FORMAT =Dynamic;
-
- SET FOREIGN_KEY_CHECKS =1;
-
- 复制代码

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version></dependency>复制代码
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>复制代码
- package com.shardingspherejdbc.mybatisplus.genertor;
-
- import com.baomidou.mybatisplus.annotation.FieldFill;
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.generator.FastAutoGenerator;
- import com.baomidou.mybatisplus.generator.config.OutputFile;
- import com.baomidou.mybatisplus.generator.config.rules.DateType;
- import com.baomidou.mybatisplus.generator.fill.Column;
- import com.baomidou.mybatisplus.generator.fill.Property;
- import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine;
-
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * 代码生成器
- *
- * @author: austin
- * @since: 2023/2/6 15:28
- */publicclassCodeGenerator {
- publicstaticvoidmain(String[] args) {
- // 数据源配置
- FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin")
- .globalConfig(builder -> {
- builder.author("austin") // 设置作者
- .enableSwagger() // 开启 swagger 模式 默认值:false
- .disableOpenDir() // 禁止打开输出目录 默认值:true
- .commentDate("yyyy-MM-dd") // 注释日期
- .dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
- .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录
- })
-
- .packageConfig(builder -> {
- builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模块名
- .controller("controller") //Controller 包名 默认值:controller
- .entity("entity") //Entity 包名 默认值:entity
- .service("service") //Service 包名 默认值:service
- .mapper("mapper") //Mapper 包名 默认值:mapper
- .other("model")
- //.moduleName("xxx") // 设置父包模块名 默认值:无
- .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径//默认存放在mapper的xml下
- })
-
- .injectionConfig(consumer -> {
- Map<String, String> customFile = newHashMap<>();
- // DTO、VO
- customFile.put("DTO.java", "/templates/entityDTO.java.ftl");
- customFile.put("VO.java", "/templates/entityVO.java.ftl");
-
- consumer.customFile(customFile);
- })
-
- .strategyConfig(builder -> {
- builder.addInclude("user") // 设置需要生成的表名 可边长参数“user”, “user1”
- .addTablePrefix("tb_", "gms_") // 设置过滤表前缀
- .serviceBuilder()//service策略配置
- .formatServiceFileName("%sService")
- .formatServiceImplFileName("%sServiceImpl")
- .entityBuilder()// 实体类策略配置
- .idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id
- .addTableFills(newColumn("create_time", FieldFill.INSERT)) // 自动填充配置
- .addTableFills(newProperty("update_time", FieldFill.INSERT_UPDATE))
- .enableLombok() //开启lombok
- .logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段
- .enableTableFieldAnnotation()// 属性加上注解说明
- .controllerBuilder() //controller 策略配置
- .formatFileName("%sController")
- .enableRestStyle() // 开启RestController注解
- .mapperBuilder()// mapper策略配置
- .formatMapperFileName("%sMapper")
- .enableMapperAnnotation()//@mapper注解开启
- .formatXmlFileName("%sMapper");
- })
-
-
- // 使用Freemarker引擎模板,默认的是Velocity引擎模板//.templateEngine(new FreemarkerTemplateEngine())
- .templateEngine(newEnhanceFreemarkerTemplateEngine())
- .execute();
-
- }
- }
- 复制代码

- package com.shardingspherejdbc.mybatisplus.engine;
-
- import com.baomidou.mybatisplus.generator.config.OutputFile;
- import com.baomidou.mybatisplus.generator.config.po.TableInfo;
- import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
- import org.springframework.stereotype.Component;
-
- import java.io.File;
- import java.util.Map;
-
- /**
- * 代码生成器支持自定义[DTO\VO等]模版
- *
- * @author: austin
- * @since: 2023/2/9 13:00
- */@ComponentpublicclassEnhanceFreemarkerTemplateEngineextendsFreemarkerTemplateEngine {
-
- @OverrideprotectedvoidoutputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
- String entityName = tableInfo.getEntityName();
- String otherPath = this.getPathInfo(OutputFile.other);
- customFile.forEach((key, value) -> {
- String fileName = String.format(otherPath + File.separator + entityName + "%s", key);
- this.outputFile(newFile(fileName), objectMap, value, true);
- });
- }
- }
- 复制代码

未生成代码前的项目目录如下:
运行CodeGenerator生成代码:
- 14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
- 14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show table status WHERE 1=1 AND NAME IN ('user')
- 14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:1,耗时(ms):26
- 14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `user`
- 14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[user]的主键为自增主键,会导致全局主键的ID类型设置失效!
- 14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:5,耗时(ms):14
- 14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================
- 复制代码
项目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。
- package com.shardingspherejdbc.mybatisplus.entity;
-
- import com.baomidou.mybatisplus.annotation.FieldFill;
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import io.swagger.annotations.ApiModel;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.Getter;
- import lombok.Setter;
-
- import java.io.Serializable;
- import java.util.Date;
-
- /**
- * <p>
- * 用户
- * </p>
- *
- * @author austin
- * @since 2023-02-09
- */@Getter@Setter@TableName("user")@ApiModel(value = "User对象", description = "用户")publicclassUserimplementsSerializable {
-
- private static final long serialVersionUID = 1L;
-
- @TableId(value = "id", type = IdType.AUTO)privateLong id;
-
- @ApiModelProperty("用户名")@TableField("username")private String username;
-
- @ApiModelProperty("手机号")@TableField("mobile")private String mobile;
-
- @ApiModelProperty("创建人")@TableField("create_by")private String createBy;
-
- @ApiModelProperty("创建时间")@TableField(value = "create_time", fill = FieldFill.INSERT)private Date createTime;
-
-
- }
- 复制代码

想了解MyBatis Plus代码生成配置可以参考官方配置: 代码生成器配置新
作者:austin流川枫
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。