Mybatis-Plus新版代码生成器使用,SpringBoot3.0+JDK17 整合Mybatis-Plus,Mybatis-Plus生成器及模板新旧对比。

文章目录

    • Mybatis-Plus代码生成器(新)
    • Mybatis-Plus代码生成器(旧)

在公司开发的新项目,使用到的是SpringBoot3.0+JDK17 ,顺带也将mybatis-plus的版本给提升了,升级了后发现老的代码生成器没办法使用了哎。那就浅记录下叭。

参考官网:https://baomidou.com/pages/d357af

Mybatis-Plus代码生成器(新)

 <!--MyBaitsPlus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>

版本3.5.3.1
在官网都有详细的配置说明:
Mybatis-Plus新版代码生成器使用,SpringBoot3.0+JDK17 整合Mybatis-Plus,Mybatis-Plus生成器及模板新旧对比。_第1张图片

直接上代码:

package com.youming.client;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
import com.youming.client.commons.base.BaseController;
import com.youming.client.commons.base.BaseDomain;
import com.youming.client.commons.base.BaseServiceImpl;
import com.youming.client.commons.base.IBaseService;

public class MyBatisPlusGenerator {

    private static final String AUTHOR = "xii";

    private static final String USER_DIR = System.getProperty("user.dir");

    private static final String JDBC_URL = "jdbc:mysql://XXXXXXXXX";

    private static final String JDBC_PASSWORD = "123456";
    private static final String JDBC_USERNAME = "root";

    /**
     * 包配置 -父级目录
     */
    private static final String PACKAGE_PARENT = "com.XXXXXX";

    /**
     * 包配置--模块目录,
     */
    private static final String PACKAGE_MODULE_NAME = "alarm";


    /**
     * 包配置 - 实体类目录
     */
    private static final String PACKAGE_ENTITY = "domain";

    /**
     * 包配置 - 数据访问接口目录
     */
    private static final String PACKAGE_MAPPER = "mapper";

    /**
     * 包配置 - 业务处理接口目录
     */
    private static final String PACKAGE_SERVICE = "api";

    /**
     * 包配置 - 业务处理实现目录
     */
    private static final String PACKAGE_SERVICE_IMPL = "service";

    /**
     * 包配置 - 控制器目录
     */
    private static final String PACKAGE_CONTROLLER = "controller";

    /**
     * 要生成的表,用','分隔
     */
    private static final String TABLES = "alarm_record";

    /**
     * 通用包路径
     */
    private static final String PACKAGE_BASE = "com.youming.client.commons.base";

    /**
     * 全局配置
     *
     * @return {@link GlobalConfig}
     */
    private static GlobalConfig globalConfig() {
        GlobalConfig config = new GlobalConfig.Builder().author(AUTHOR).outputDir(USER_DIR + "/src/main/java").build();
        return config;
    }

    /**
     * 数据源配置
     */
    private static DataSourceConfig dataSourceConfig() {
        DataSourceConfig config = new DataSourceConfig.Builder(JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD)
                .typeConvert(new MySqlTypeConvert())
                .keyWordsHandler(new MySqlKeyWordsHandler())
                .build();;
        return config;
    }

    /**
     * 包配置
     */
    private static PackageConfig packageConfig() {
        PackageConfig config = new PackageConfig.Builder()
                .parent(PACKAGE_PARENT)
                .moduleName(PACKAGE_MODULE_NAME)
                .entity(PACKAGE_ENTITY)
                .service(PACKAGE_SERVICE)
                .serviceImpl(PACKAGE_SERVICE_IMPL)
                .mapper(PACKAGE_MAPPER)
                .xml("mapper.xml")
                .controller(PACKAGE_CONTROLLER)
//                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://"))
                .build();
        return config;
    }

    /**
     * 代码生成模板配置-freemarker
     */
    private static TemplateConfig templateConfig() {
        TemplateConfig config = new TemplateConfig.Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .xml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();
        return config;
    }

    /***
     * 代码生成策略配置
     * */
    private static StrategyConfig strategyConfig() {

        StrategyConfig config = new StrategyConfig.Builder()
                .enableCapitalMode()
                .enableSkipView()
                .disableSqlFilter()
//                .likeTable(new LikeTable("USER"))
                .addInclude(TABLES.split(","))
                .addTablePrefix(packageConfig().getModuleName() + "_")
                .controllerBuilder() //controller层
                .enableFileOverride()
                .enableRestStyle()
                .superClass(BaseController.class)
//                .enableHyphenStyle()
                .enableRestStyle()
                .entityBuilder()//实体类
                .superClass(BaseDomain.class)
                .enableLombok()
                .enableFileOverride()
                .serviceBuilder() //service层
                .enableFileOverride()
                .superServiceClass(IBaseService.class)  //模板中需要继承的类
                .superServiceImplClass(BaseServiceImpl.class)
                .build();
//                .addFieldSuffix("_flag")


        return config;
    }

    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator(dataSourceConfig());
        generator.strategy(strategyConfig());
        generator.global(globalConfig());
        generator.packageInfo(packageConfig());
        generator.template(templateConfig());
        generator.execute();

    }
}

模板:
controller.java.ftl

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

<#if restControllerStyle>
    import org.springframework.web.bind.annotation.RestController;
<#else>
    import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
    import ${superControllerClassPackage};
</#if>
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};


/**
* 

* ${table.comment!} 前端控制器 *

* @author ${author} * @since ${date} */
<#if restControllerStyle> @RestController <#else> @Controller </#if> @RequestMapping("<#if controllerMappingHyphenStyle??>${controllerMappingHyphen?replace("-","/")}<#else>${table.entityPath?replace("-","/")}") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if> <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass}<${entity},${table.serviceName}> { <#else> public class ${table.controllerName} { </#if> } </#if>

entity.java.ftl

package ${package.Entity};

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

/**
* 

* ${table.comment!} *

* @author ${author} * @since ${date} */
<#if entityLombokModel> @Data <#if superEntityClass??> @EqualsAndHashCode(callSuper = true) <#else> @EqualsAndHashCode(callSuper = false) </#if> @Accessors(chain = true) </#if> <#if table.convert> @TableName("${table.name}") </#if> <#if swagger2> @ApiModel(value="${entity}对象", description="${table.comment!}") </#if> <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity} implements Serializable { </#if> <#if entitySerialVersionUID> private static final long serialVersionUID = 1L; </#if> <#-- @Builder--> <#-- public ${entity}(Long id,<#list table.fields as field>${field.propertyType} ${field.propertyName}<#if field_has_next>,</#if></#list>){--> <#-- super(id);--> <#-- <#list table.fields as field>--> <#-- this.${field.propertyName}=${field.propertyName};--> <#-- </#list>--> <#-- }--> <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> </#if> <#if field.comment!?length gt 0> <#if swagger2> @ApiModelProperty(value = "${field.comment}") <#else> /** * ${field.comment} */ </#if> </#if> <#if field.keyFlag> <#-- 主键 --> <#if field.keyIdentityFlag> @TableId(value = "${field.name}", type = IdType.AUTO) <#elseif idType??> @TableId(value = "${field.name}", type = IdType.${idType}) <#elseif field.convert> @TableId("${field.name}") </#if> <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) </#if> <#elseif field.convert> @TableField("${field.name}") </#if> <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version </#if> <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @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 entityBuilderModel> 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 entityBuilderModel> 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 protected 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> }

mapper.java.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
* 

* ${table.comment!}Mapper接口 *

* @author ${author} * @since ${date} */
<#if kotlin> interface ${table.mapperName} : ${superMapperClass}<${entity}> <#else> public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { } </#if>

mapper.xml.ftl

<?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="${package.Mapper}.${table.mapperName}">

    <#if enableCache>
        <!-- 开启二级缓存 -->
        <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

    </#if>
    <#if baseResultMap>
        <!-- 通用查询映射结果 -->
        <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
            <#list table.fields as field>
                <#if field.keyFlag>
                    <#--生成主键排在第一位-->
                    <id column="${field.name}" property="${field.propertyName}" />
                </#if>
            </#list>
            <#list table.commonFields as field>
            <#--生成公共字段 -->
                <result column="${field.name}" property="${field.propertyName}" />
            </#list>
            <#list table.fields as field>
                <#if !field.keyFlag>
                <#--生成普通字段 -->
                    <result column="${field.name}" property="${field.propertyName}" />
                </#if>
            </#list>
        </resultMap>

    </#if>
    <#if baseColumnList>
        <!-- 通用查询结果列 -->
        <sql id="Base_Column_List">
            <#list table.commonFields as field>
                ${field.name},
            </#list>
            ${table.fieldNames}
        </sql>

    </#if>
</mapper>

service.java.ftl

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* 

* ${table.comment!} 服务类 *

* @author ${author} * @since ${date} */
<#if kotlin> interface ${table.serviceName} : ${superServiceClass}<${entity}> <#else> public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { } </#if>

serviceImpl.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;


/**
* 

* ${table.comment!} 服务实现类 *

* @author ${author} * @since ${date} */
@Service <#if kotlin> open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { } <#else> public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { } </#if>

运行main方法

Mybatis-Plus新版代码生成器使用,SpringBoot3.0+JDK17 整合Mybatis-Plus,Mybatis-Plus生成器及模板新旧对比。_第2张图片

这样就生成了

Mybatis-Plus代码生成器(旧)

 <!--MyBaitsPlus-->
        <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.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

Mybatis-Plus新版代码生成器使用,SpringBoot3.0+JDK17 整合Mybatis-Plus,Mybatis-Plus生成器及模板新旧对比。_第3张图片

整理过后的工具类:

package com.youming.shuiku;

import com.baomidou.mybatisplus.annotation.FieldFill;
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.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

public class MyBatisPlusGenerator {

    private static final String AUTHOR = "xxx";//作者

    private static final String USER_DIR = System.getProperty("user.dir");

    private static final String JDBC_URL = "jdbc:mysql://------------------------";//数据库路径

    private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    private static final String JDBC_PASSWORD = "123456";
    private static final String JDBC_USERNAME = "root";

    /**
     * 包配置 -父级目录
     */
    private static final String PACKAGE_PARENT = "com.XX.XX";

    /**
     * 包配置--模块目录,
     */
    private static final String PACKAGE_MODULE_NAME = "XX";


    /**
     * 包配置 - 实体类目录
     */
    private static final String PACKAGE_ENTITY = "XX.domain";

    /**
     * 包配置 - 数据访问接口目录
     */
    private static final String PACKAGE_MAPPER = "XX.mapper";

    /**
     * 包配置 - 业务处理接口目录
     */
    private static final String PACKAGE_SERVICE = "XX.api";

    /**
     * 包配置 - 业务处理实现目录
     */
    private static final String PACKAGE_SERVICE_IMPL = "XX.service";

    /**
     * 包配置 - 控制器目录
     */
    private static final String PACKAGE_CONTROLLER = "XX.controller";

    /**
     * 要生成的表,用','分隔
     */
    private static final String TABLES = "app_upload";//表名

    /**
     * 通用包路径   用于模板中类的导包
     */
    private static final String PACKAGE_BASE = "com.youming.shuiku.commons.base";

    /**
     * 全局配置
     *
     * @return {@link GlobalConfig}
     */
    private static GlobalConfig globalConfig() {
        GlobalConfig config = new GlobalConfig();
        config.setOutputDir(USER_DIR + "/src/main/java");
        config.setAuthor(AUTHOR);
        config.setOpen(false);
        return config;
    }

    /**
     * 数据源配置
     */
    private static DataSourceConfig dataSourceConfig() {
        DataSourceConfig config = new DataSourceConfig();
        config.setUrl(JDBC_URL);
        config.setDriverName(JDBC_DRIVER_NAME);
        config.setUsername(JDBC_USERNAME);
        config.setPassword(JDBC_PASSWORD);
        return config;
    }

    /**
     * 包配置
     */
    private static PackageConfig packageConfig() {
        PackageConfig config = new PackageConfig();
        config.setParent(PACKAGE_PARENT);
        config.setModuleName(PACKAGE_MODULE_NAME);

        config.setEntity(PACKAGE_ENTITY);
        config.setMapper(PACKAGE_MAPPER);
        config.setService(PACKAGE_SERVICE);
        config.setServiceImpl(PACKAGE_SERVICE_IMPL);
        config.setController(PACKAGE_CONTROLLER);
        return config;
    }

    /**
     * 代码生成模板配置-freemarker
     */
    private static TemplateConfig templateConfig() {
        TemplateConfig config = new TemplateConfig();
        config.setEntity("templates/entity.java");
        config.setMapper("templates/mapper.java");
        config.setService("templates/service.java");
        config.setServiceImpl("templates/serviceImpl.java");
        config.setController("templates/controller.java");
        config.setXml(null);
        return config;
    }

    /***
     * 代码生成策略配置
     * */
    private static StrategyConfig strategyConfig() {
        //策列配置,数据库表配置
        StrategyConfig config = new StrategyConfig();
        // 数据库表映射到实体类的命名策略
        config.setNaming(NamingStrategy.underline_to_camel);
        // 数据库表字段映射到实体类的命名策略
        config.setColumnNaming(NamingStrategy.underline_to_camel);
        // 实体是否为lombok
        config.setEntityLombokModel(true);
        config.setInclude(TABLES.split(","));
        // 驼峰转
        config.setControllerMappingHyphenStyle(true);

        // TEST 风格
        config.setRestControllerStyle(true);
        // 表前缀
      //  config.setTablePrefix(packageConfig().getModuleName() + "_");


        // 字段填充
        List<TableFill> tableFills = new ArrayList<>();
        tableFills.add(new TableFill("create_time", FieldFill.INSERT));
        tableFills.add(new TableFill("update_time", FieldFill.INSERT_UPDATE));
        tableFills.add(new TableFill("is_deleted", FieldFill.INSERT));
        config.setTableFillList(tableFills);


        // commonBase
        config.setSuperEntityColumns("id","create_time","update_time");
        config.setSuperEntityClass(PACKAGE_BASE.concat(".BaseDomain"));
        config.setSuperServiceClass(PACKAGE_BASE.concat(".IBaseService"));
        config.setSuperServiceImplClass(PACKAGE_BASE.concat(".BaseServiceImpl"));
        config.setSuperControllerClass(PACKAGE_BASE.concat(".BaseController"));


        return config;
    }

    /**
     * 自定义配置
     */
    private static InjectionConfig injectionConfig() {
        InjectionConfig config = new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };

        // 自定义输出 mapper.xml到resources 目录下
        String mapperPath = "/templates/mapper.xml.ftl";
        List<FileOutConfig> outConfigList = new ArrayList<>();
        outConfigList.add(new FileOutConfig(mapperPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名,如果你Entity 设置了前后缀,此处的xml名称会跟随发生变化
                return USER_DIR + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        config.setFileOutConfigList(outConfigList);
        return config;
    }

    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator();
        generator.setGlobalConfig(globalConfig());
        generator.setDataSource(dataSourceConfig());
        generator.setPackageInfo(packageConfig());
        generator.setTemplate(templateConfig());
        generator.setTemplateEngine(new FreemarkerTemplateEngine());
        generator.setCfg(injectionConfig());
        generator.setStrategy(strategyConfig());
        generator.execute();

    }
}

模板:
可以根据需要修改,我这里使用了微服务
controller.java.ftl

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

<#if restControllerStyle>
    import org.springframework.web.bind.annotation.RestController;
<#else>
    import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
    import ${superControllerClassPackage};
</#if>
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import org.apache.dubbo.config.annotation.DubboReference;

/**
* 

* ${table.comment!} 前端控制器 *

* @author ${author} * @since ${date} */
<#if restControllerStyle> @RestController <#else> @Controller </#if> @RequestMapping("<#if controllerMappingHyphenStyle??>${controllerMappingHyphen?replace("-","/")}<#else>${table.entityPath?replace("-","/")}") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if> <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass}<${entity},${table.serviceName}> { <#else> public class ${table.controllerName} { </#if> @DubboReference(version = "1.0.0") ${table.serviceName} ${table.serviceName?substring(1,table.serviceName?length?number)?uncap_first}; @Override public ${table.serviceName} getService() { return ${table.serviceName?substring(1,table.serviceName?length?number)?uncap_first}; } } </#if>

entity.java.ftl

package ${package.Entity};

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

/**
* 

* ${table.comment!} *

* @author ${author} * @since ${date} */
<#if entityLombokModel> @Data <#if superEntityClass??> @EqualsAndHashCode(callSuper = true) <#else> @EqualsAndHashCode(callSuper = false) </#if> @Accessors(chain = true) </#if> <#if table.convert> @TableName("${table.name}") </#if> <#if swagger2> @ApiModel(value="${entity}对象", description="${table.comment!}") </#if> <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity} implements Serializable { </#if> <#if entitySerialVersionUID> private static final long serialVersionUID = 1L; </#if> <#-- @Builder--> <#-- public ${entity}(Long id,<#list table.fields as field>${field.propertyType} ${field.propertyName}<#if field_has_next>,</#if></#list>){--> <#-- super(id);--> <#-- <#list table.fields as field>--> <#-- this.${field.propertyName}=${field.propertyName};--> <#-- </#list>--> <#-- }--> <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> </#if> <#if field.comment!?length gt 0> <#if swagger2> @ApiModelProperty(value = "${field.comment}") <#else> /** * ${field.comment} */ </#if> </#if> <#if field.keyFlag> <#-- 主键 --> <#if field.keyIdentityFlag> @TableId(value = "${field.name}", type = IdType.AUTO) <#elseif idType??> @TableId(value = "${field.name}", type = IdType.${idType}) <#elseif field.convert> @TableId("${field.name}") </#if> <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) </#if> <#elseif field.convert> @TableField("${field.name}") </#if> <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version </#if> <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @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 entityBuilderModel> 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 entityBuilderModel> 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 protected 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> }

mapper.java.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
* 

* ${table.comment!}Mapper接口 *

* @author ${author} * @since ${date} */
<#if kotlin> interface ${table.mapperName} : ${superMapperClass}<${entity}> <#else> public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { } </#if>

mapper.xml.ftl

<?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="${package.Mapper}.${table.mapperName}">

    <#if enableCache>
        <!-- 开启二级缓存 -->
        <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

    </#if>
    <#if baseResultMap>
        <!-- 通用查询映射结果 -->
        <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
            <#list table.fields as field>
                <#if field.keyFlag>
                    <#--生成主键排在第一位-->
                    <id column="${field.name}" property="${field.propertyName}" />
                </#if>
            </#list>
            <#list table.commonFields as field>
            <#--生成公共字段 -->
                <result column="${field.name}" property="${field.propertyName}" />
            </#list>
            <#list table.fields as field>
                <#if !field.keyFlag>
                <#--生成普通字段 -->
                    <result column="${field.name}" property="${field.propertyName}" />
                </#if>
            </#list>
        </resultMap>

    </#if>
    <#if baseColumnList>
        <!-- 通用查询结果列 -->
        <sql id="Base_Column_List">
            <#list table.commonFields as field>
                ${field.name},
            </#list>
            ${table.fieldNames}
        </sql>

    </#if>
</mapper>

service.java.ftl

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* 

* ${table.comment!} 服务类 *

* @author ${author} * @since ${date} */
<#if kotlin> interface ${table.serviceName} : ${superServiceClass}<${entity}> <#else> public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { } </#if>

serviceImpl.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.apache.dubbo.config.annotation.DubboService;


/**
* 

* ${table.comment!} 服务实现类 *

* @author ${author} * @since ${date} */
<#--@Service--> @DubboService(version = "1.0.0") <#if kotlin> open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { } <#else> public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { } </#if>

运行工具类中的方法。就可以

Mybatis-Plus新版代码生成器使用,SpringBoot3.0+JDK17 整合Mybatis-Plus,Mybatis-Plus生成器及模板新旧对比。_第4张图片

你可能感兴趣的:(Mybatis-Plus,mybatis,java,开发语言)