MyBatis-Plus代码生成controller,entity,mapper,service层

        最近在处理业务的时候,有太多的表需要生成entity,controller等业务与处理模块了,之前一直使用idea连接数据库,再安装插件,即可生成相应的模块,今天换一种方式来实现。话不多说直接上代码 

一、添加依赖  

        全新的代码生成器添加于 3.5.1 版本,且对历史版本不兼容!如果使用的是 3.5.1 以下的版本,请参考 代码生成器 进行配置与使用。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>

二、配置设置

        这里实体类因需要添加注解,所以编写了自定义的模版myentity.java.ftl

@Slf4j
public class MyBatisPlusGenerator {

    public static void main(String[] args) {
    List<String> tables = new ArrayList<>();
    tables.add("org_info");
    
    FastAutoGenerator.create(
            "数据库连接路径", 
            "用户", 
            "密码"
        )
        .globalConfig(builder -> {
            builder.author("QT") // 设置作者名称
                   .outputDir(System.getProperty("user.dir") + "\\SayAo\\src\\main\\java") // 设置生成文件的输出路径
                   .enableSwagger() // 启用 Swagger 注解
                   .commentDate("yyyy-MM-dd") // 设置注释日期格式
                   .fileOverride(); // 启用文件覆盖
        })
        .packageConfig(builder -> {
            builder.parent("com.ali") // 设置父包名
                   .moduleName("sayao") // 设置模块名
                   .entity("model") // 设置实体类包名
                   .service("service") // 设置 Service 包名
                   .serviceImpl("service.impl") // 设置 Service 实现类包名
                   .controller("controller") // 设置 Controller 包名
                   .mapper("mapper") // 设置 Mapper 接口包名
                   .xml("mapper") // 设置 Mapper XML 文件包名
                   .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "\\SayAo\\src\\main\\resources\\mapper")); // 设置 Mapper XML 文件的输出路径
        })
        .strategyConfig(builder -> {
            builder.addInclude(tables) // 指定需要生成代码的表
                   .serviceBuilder()
                   .formatServiceFileName("%sService") // 设置 Service 接口文件名格式
                   .formatServiceImplFileName("%sServiceImpl") // 设置 Service 实现类文件名格式
                   .entityBuilder()
                   .enableLombok() // 启用 Lombok 注解
                   .enableTableFieldAnnotation() // 启用实体类字段注解
                   .controllerBuilder()
                   .enableHyphenStyle() // 启用连字符格式的映射路径
                   .formatFileName("%sController") // 设置 Controller 文件名格式
                   .enableRestStyle() // 启用 Rest 风格
                   .mapperBuilder()
                   .enableBaseResultMap() // 启用通用的 resultMap
                   .superClass(BaseMapper.class) // 设置 Mapper 的父类
                   .formatMapperFileName("%sMapper") // 设置 Mapper 文件名格式
                   .enableMapperAnnotation() // 启用 Mapper 注解
                   .formatXmlFileName("%sMapper"); // 设置 Mapper XML 文件名格式
        })
        .templateConfig(builder -> builder.entity("templates/myentity.java")) // 使用自定义的实体类模板
        .templateEngine(new FreemarkerTemplateEngine()) // 使用 Freemarker 引擎模板
        .execute();
}
}

三、ftl模版

        这段代码是一个用于生成 Java 实体类的 FreeMarker 模板,它根据指定的配置和数据库表结构动态生成实体类的代码。(按自己需求进行修改,这里主要是需要添加swagger与mybatisplus提供的注解)

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
<#if chainModel>
import lombok.experimental.Accessors;
</#if>
</#if>

/**
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if chainModel>
@Accessors(chain = true)
</#if>
</#if>
<#if table.convert>
@TableName("${schemaName}${table.name}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#elseif entitySerialVersionUID>
public class ${entity} implements Serializable {
<#else>
public class ${entity} {
</#if>
<#if entitySerialVersionUID>

    private static final long serialVersionUID = 1L;
</#if>
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.comment!?length gt 0>
        <#if swagger>
        @ApiModelProperty("${field.comment}")
        <#else>
            /**
            * ${field.comment}
            */
        </#if>
    </#if>
    <#if field.keyFlag>
    <#-- 主键 -->
    <#if field.keyIdentityFlag>
    @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
    <#elseif idType??>
    @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
    <#elseif field.convert>
    @TableId("${field.annotationColumnName}")
    </#if>
    <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
    <#if field.convert>
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
    <#else>
    @TableField(fill = FieldFill.${field.fill})
    </#if>
    <#elseif field.convert>
    @TableField("${field.annotationColumnName}")
    </#if>
<#-- 乐观锁注解 -->
    <#if field.versionField>
    @Version
    </#if>
<#-- 逻辑删除注解 -->
    <#if field.logicDeleteField>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循环遍历  ---------->

<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
        public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
        }

        <#if chainModel>
            public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
            public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if chainModel>
            return this;
        </#if>
        }
    </#list>
</#if>

<#if entityColumnConstant>
    <#list table.fields as field>
    public static final String ${field.name?upper_case} = "${field.name}";

    </#list>
</#if>
<#if activeRecord>
    @Override
    public Serializable pkVal() {
    <#if keyPropertyName??>
        return this.${keyPropertyName};
    <#else>
        return null;
    </#if>
    }

</#if>
<#if !entityLombokModel>
    @Override
    public String toString() {
    return "${entity}{" +
    <#list table.fields as field>
        <#if field_index==0>
            "${field.propertyName}=" + ${field.propertyName} +
        <#else>
            ", ${field.propertyName}=" + ${field.propertyName} +
        </#if>
    </#list>
    "}";
    }
</#if>
}




主打一个爱分享,结束~~~~~~

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: mybatis-plus 是一个基于 MyBatis 的增强工具,在实现 MyBatis 基本功能的同时,提供了很多实用的增强功能,例如:自动代码生成、分页插件、性能分析插件、乐观锁插件等。 mybatis-plus代码生成器可以快速生成实体类、mapper 接口、mapper.xml 文件等。使用代码生成器可以减少重复劳动,提高开发效率。使用 mybatis-plus代码生成器需要在配置文件中添加相关配置,例如:数据库连接信息、生成文件路径、生成策略等。配置完成后,运行代码生成器即可生成相关文件。 下面是一个使用 mybatis-plus 代码生成器的示例: 1.在 pom.xml 文件中添加依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>最新版本</version> </dependency> ``` 2.在配置文件中添加相关配置: ``` # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root # mybatis-plus 代码生成器配置 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0 mybatis-plus.generator.outputDir=src/main/java mybatis-plus.generator.author=作者 mybatis-plus.generator.serviceName=%sService mybatis-plus.generator.mapperName=%sMapper mybatis-plus.generator.xmlName=%sMapper mybatis-plus.generator.tableName=表名 ``` 3.运行代码生成器 ``` public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); gc.setAuthor("作者"); gc.setOpen(false); gc.setServiceName("%sService"); gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setBaseResultMap(true); gc.setBaseColumnList(true); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.example"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.impl"); pc.setController("controller"); mpg.setPackageInfo(pc); // 策略配置 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); strategy.setInclude("表名"); strategy.setLogicDeleteFieldName("deleted"); strategy.setVersionFieldName("version"); strategy.setTablePrefix("t_"); mpg.setStrategy(strategy); //mybatis-plus 是一个基于 MyBatis 的增强工具,它能够简化 MyBatis 的使用,提高开发效率,减少开发人员的重复工作。它能够自动生成 MyBatismapper 以及 XML 文件,支持常用的 CRUD 操作,还提供了许多实用的特性,如分页、逻辑删除、多租户支持等。 使用 mybatis-plus代码生成器可以进一步提高开发效率。代码生成器能够根据数据库表自动生成 entitymapperservicecontroller 等基础代码,极大地减少了开发人员的编码工作量。使用 mybatis-plus 代码生成器可以快速生成标准化的代码,提高代码的可读性和可维护性,同时也减少了开发人员的错误率。 要使用 mybatis-plus 代码生成器,首先需要在项目中添加 mybatis-plus 依赖,然后在配置文件中指定数据库连接信息、生成代码的包路径等相关信息。在配置完成后,运行代码生成器即可自动生成基础代码。 ### 回答2: Mybatis-Plus 代码生成器是一种能够帮助开发者快速生成 Mybatis-Plus 代码的工具。该工具是基于 Mybatis-Plus 和 Velocity 模板引擎开发的,使用它可以大大提升开发效率,减少代码重复工作。 Mybatis-Plus 代码生成器支持生成多种类型的代码文件,包括 EntityMapperServiceController 等,还能够自动生成基本的 CRUD 方法,避免了开发者手动编写这些方法的繁琐过程。此外,代码生成器还支持自定义模板文件,可以根据需求自定义生成的代码格式。 使用 Mybatis-Plus 代码生成器可以简化开发流程,减少开发人员的劳动量,提高代码的可维护性。此外,还可以统一代码规范和风格,从而提高代码的可读性和可维护性。 总体来说,Mybatis-Plus 代码生成器是一个非常实用的工具,能够提高开发效率,减少代码重复工作,值得开发人员学习和使用。同时,在使用代码生成器的过程中也需要注意不要过度依赖,需要根据实际需求进行选择和使用。 ### 回答3: Mybatis-Plus是一款优秀的ORM框架,它的代码生成器可以大大缩短我们开发的时间成本,提高我们的代码质量和可读性。下面我们来详细介绍一下Mybatis-Plus代码生成器的使用。 Mybatis-Plus代码生成器主要有如下功能: 1. 自动生成实体类 代码生成器可以根据我们的数据库表结构自动生成对应的实体类。我们只需要配置好数据库连接信息以及对应的表名,就可以生成JavaBean,并且可以指定实体名和字段名的命名规则。生成的实体类中包含了对应表中的字段以及 setter和getter方法。 2. 自动生成MapperMapper类是我们用来操作数据库的接口,代码生成器可以根据我们配置的表结构自动生成Mapper接口,并且让我们能够通过注解的方式进行SQL语句的编写。同时,生成Mapper类也包含了一些Mybatis-Plus自带的基本方法,如增删改查等。 3. 自动生成XML映射文件 XML映射文件是我们用于将Java和数据库中数据进行映射的文件。代码生成器可以根据我们的表结构自动生成对应的XML文件,并且让我们可以在其中使用自定义的SQL语句,以及Mybatis-Plus自带的一些SQL语句。 使用Mybatis-Plus代码生成器的优点: 1. 减少编写代码的工作量 代码生成器可以根据我们的表结构自动生成大量的Java和XML代码,减少我们的编写代码的工作量,同时让我们不容易犯错。 2. 缩短开发周期 通过使用代码生成器,我们可以快速生成Java代码,并且可以直接运行自己的SQL语句。这使得我们可以更快地上手项目,并且缩短开发周期。 3. 提高代码质量和可读性 代码生成器能够根据我们的表结构生成代码,这使得我们的代码质量更高,并且让代码更易于阅读和维护。同时,代码生成器会自动将代码规范化,这使得我们的代码更加规范和统一。 总结: Mybatis-Plus代码生成器是一个非常实用的工具,能够大大缩短我们的开发时间和工作量,提高我们的代码质量和可读性。同时,它还具有非常多的灵活性和自定义功能,可以满足不同开发人员的需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值