MyBatis-Plus使用 Generator 代码生成器生成实体类支持Swagger2

点击上方 "编程技术圈"关注, 星标或置顶一起成长

后台回复“大礼包”有惊喜礼包!

日英文

When faced with two choices, simply toss a coin.because in that brief moment when the coin is in the air, you suddenly know what you are hoping for. 

当面对两个选择时,抛硬币总能奏效,因为在你把它抛在空中的那一秒里,你突然知道你希望它是什么! 

每日掏心话

人生,就是这样,倘若有运,不用祈求,祈求终归无用;倘若无运,无需悲伤,悲伤终归无助。
责编:乐乐 | 来自:传说中的黑桃A链接:blog.csdn.net/sj13074480550/article/details/102976146

编程技术圈(ID:study_tech)第 1258 次推文

往日回顾:刚刚用华为鸿蒙跑了个“hello world”!跑通后,我特么开始怀疑人生....

     

   正文   

mybatis-plus使用generator代码生成器生成实体类支持Swagger2

  1. 先搭建项目,引入maven依赖

  2. 编写代码生成器代码(有说明)

  3. 在resources目录下创建templates目录

  4. 在templates目录下创建entity.java.vm模板(代码如下)

  5. 基本完成只要运行代码生成器代码,输入表名即可

使用自定义模板生成支持Swagger2的实体类,生成的@ApiModelProperty中的value值都是数据库表字段的注释,所有生成之前数据表一定要先注释好

1.先搭建项目,引入maven依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.9.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- jdbc -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- mybatis-plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.1.1</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.1.1</version>
    </dependency>
    <!-- swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- Velocity模板引擎 -->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.1</version>
    </dependency>
</dependencies>

2.编写代码生成器代码(有说明)

/**
 * @Description: 代码生成器
 * @author liangshaolian
 */
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.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        AutoGenerator generator = new AutoGenerator();
        // 全局变量配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir"); //当前项目
        gc.setOutputDir(projectPath+"/src/main/java"); // 输出路径
        gc.setFileOverride(true); // 默认 false ,是否覆盖已生成文件
        gc.setOpen(false); //默认true ,是否打开输出目录
        gc.setEnableCache(false); // 默认false,是否开启二级缓存
        gc.setAuthor("liangshaolian"); // 作者
        gc.setSwagger2(true); //默认false
        gc.setBaseResultMap(true); // 默认false
        gc.setDateType(DateType.TIME_PACK); // 时间策略 默认TIME_PACK
        gc.setBaseColumnList(true); //默认false  和basemodel相似
        gc.setEntityName("%s");
        gc.setControllerName("%sController");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("I%sMapper");
        gc.setXmlName("%sMapper");
        gc.setIdType(IdType.AUTO); // 指定生成的主键类型
        generator.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dc = new DataSourceConfig();
        dc.setDbQuery(new MySqlQuery()); // 数据库信息查询 //默认mysql
        dc.setDbType(DbType.MYSQL);// 数据库类型
        dc.setTypeConvert(new MySqlTypeConvert()); //类型转换 默认mysql
        dc.setUrl("jdbc:mysql://127.0.0.1:3306/数据库名?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&useSSL=false");
        dc.setDriverName("com.mysql.cj.jdbc.Driver");
        dc.setUsername("root");
        dc.setPassword("密码");
        generator.setDataSource(dc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.liang.module");//代码生成到哪个包下面
//        pc.setModuleName(""); //此处是所属模块名称
//        pc.setEntity("entity"); //默认entity,controller,service,service.impl,mapper,mapper.xml
        generator.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        /**
         * 将xml生成到resource下面
         */
        String templatePath = "/templates/mapper.xml.vm"; // Velocity模板
        // 自定义输出配置
        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.setFileOutConfigList(focList);
        generator.setCfg(cfg);

        // 配置模板
        TemplateConfig tc = new TemplateConfig();
        // templates/entity.java 模板路径配置,默认在templates目录下,.vm 后缀不用加
        tc.setEntity("templates/entity.java");//使用自定义模板生成实体类
        tc.setXml("");
        generator.setTemplate(tc);

        // 数据库表配置
        StrategyConfig sc = new StrategyConfig();
        sc.setCapitalMode(false); //是否大写命名 默认false
        sc.setSkipView(true); //是否跳过试图 默认false
        sc.setNaming(NamingStrategy.underline_to_camel);// 表映射 驼峰命名
        sc.setColumnNaming(NamingStrategy.underline_to_camel); // 字段映射 驼峰
        sc.setEntityLombokModel(true); //是否使用lombak 默认为false
        sc.setRestControllerStyle(true); // 默认false
        sc.setEntitySerialVersionUID(true); //默认true
        sc.setEntityColumnConstant(true); //默认false 将mysql字段名生成静态变量
        sc.setInclude(scanner("表名,多个英文逗号分割").split(",")); //表名,用,隔开  需要生产
   //     sc.setExclude(""); //                 不需要生成  二选一
        sc.setEntityTableFieldAnnotationEnable(true); // 默认false 注释
        sc.setControllerMappingHyphenStyle(false); //默认false
        sc.setLogicDeleteFieldName("status"); // 逻辑删除字段名称
        generator.setStrategy(sc);

        // 模板引擎
        generator.setTemplateEngine(new VelocityTemplateEngine());
        generator.execute();
    }
}

3.在resources目录下创建templates目录

4.在templates目录下创建entity.java.vm模板(代码如下)

搜索公众号后端架构师后台回复“架构整洁”,获取一份惊喜礼包。

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
##import lombok.experimental.Accessors;
#end

/**
 * @Description:$!{table.comment}
 * @author ${author}
 * @since ${date}
 */
@ApiModel(value ="$!{table.comment}")
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
##@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
    #if(${field.keyFlag})
        #set($keyPropertyName=${field.propertyName})
    #end
    #if("$!field.comment" != "")
    @ApiModelProperty(value = "${field.comment}")
    #end
    #if(${field.keyFlag})
    ## 主键s
#if(${field.keyIdentityFlag})
@TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.name}")
#end
    ## 普通字段
    #elseif(${field.fill})
    ## -----   存在字段填充设置   -----
    #if(${field.convert})
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
    #else
    @TableField(fill = FieldFill.${field.fill})
    #end
    #elseif(${field.convert})
    @TableField("${field.name}")
    #end
## 乐观锁注解
    #if(${versionFieldName}==${field.name})
    @Version
    #end
## 逻辑删除注解
    #if(${logicDeleteFieldName}==${field.name})
    @TableLogic
    #end
    private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
    #foreach($field in ${table.fields})
        #if(${field.propertyType.equals("boolean")})
            #set($getprefix="is")
        #else
            #set($getprefix="get")
        #end

    public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }

    #if(${entityBuilderModel})
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
    #else
    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        #end
        this.${field.propertyName} = ${field.propertyName};
        #if(${entityBuilderModel})
        return this;
        #end
    }
    #end
#end

#if(${entityColumnConstant})
    #foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

    #end
#end
#if(${activeRecord})
@Override
protected Serializable pkVal() {
    #if(${keyPropertyName})
            return this.${keyPropertyName};
    #else
            return null;
    #end
        }
#end
#if(!${entityLombokModel})
@Override
public String toString() {
        return "${entity}{" +
    #foreach($field in ${table.fields})
        #if($!{velocityCount}==1)
                "${field.propertyName}=" + ${field.propertyName} +
        #else
                ", ${field.propertyName}=" + ${field.propertyName} +
        #end
    #end
        "}";
    }
#end
}

5.基本完成只要运行代码生成器代码,输入表名即可

生成的实体类效果如下:

/**
 * @Description:汽车品牌表
 * @author liangshaolian
 */
@ApiModel(value ="汽车品牌表")
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("tn_pur_brand")
public class TnPurBrand implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @ApiModelProperty(value = "首字母")
    @TableField("initials")
    private String initials;
    @ApiModelProperty(value = "汽车品牌")
    @TableField("brand_name")
    private String brandName;
    @ApiModelProperty(value = "品牌LOGO")
    @TableField("logo")
    private String logo;

  public static final String ID = "id";

    public static final String INITIALS = "initials";

    public static final String BRAND_NAME = "brand_name";

    public static final String LOGO = "logo";

}
PS:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。
版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢!
欢迎加入后端架构师交流群,在后台回复“学习”即可。
最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。在这里,我为大家准备了一份2021年最新最全BAT等大厂Java面试经验总结。别找了,想获取史上最简单的Java大厂面试题学习资料扫下方二维码回复「面试」就好了猜你还想看阿里、腾讯、百度、华为、京东最新面试题汇集鸿蒙OS终于来了,今天正式发布!
一名程序员自建停车缴费系统,面向监狱编程!
9名程序员被抓!这次我并不同情他们!
嘿,你在看吗?
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值