Mybatis-Plus 代碼生成器

1雪情、創(chuàng)建表sys_units_dict

image.png

2蓄诽、pom文件配置

        <!--mybatisPlus插件-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--代碼生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- 擴(kuò)展代碼生成插件 zhuwh  -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <!--geoTools外圍jar-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

3、新建生成器類(lèi)(CodeGeneratorUtils)

package com.gsgx.project.tool.generator;

/**
 * @Author: FanJiaKai
 * @Description:
 * @Date: Created in 2021/7/13 21:53
 */
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Desc: MyBatisPlus代碼生成器
 * @Author: Administrator
 * @Date: 2020/11/2320:32
 */
@SuppressWarnings("all")
public class CodeGeneratorUtils {


    /**
     * 讀取控制臺(tái)內(nèi)容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請(qǐng)輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        // gc.setOutputDir("D:\\test");
        gc.setAuthor("kk");
        //是否打開(kāi)輸出目錄
        gc.setOpen(false);
        //是否覆蓋已有文件
        gc.setFileOverride(true);
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        gc.setSwagger2(true); // 實(shí)體屬性 Swagger2 注解
        //service 命名方式
        gc.setServiceName("%sService");
        //entity 命名方式
        gc.setEntityName("%sEntity");

        mpg.setGlobalConfig(gc);

        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:postgresql://114.116.236.4:5432/traffic_survey_db");
        dsc.setDriverName("org.postgresql.Driver");
        dsc.setUsername("postgres");
        dsc.setPassword("Aolutong123!@#");
        dsc.setSchemaName("public");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.gsgx.project.demo");
        pc.setEntity("model.entity");
        pc.setMapper("dao");
//        pc.setXml("mybatis.survey");
        mpg.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                //如果不存在痕慢,創(chuàng)建;如果存在涌矢,判斷是否是entity.java:如果是掖举,創(chuàng)建(覆蓋);否則娜庇,不創(chuàng)建塔次。
                checkDir(filePath);
                File file = new File(filePath);
                boolean exist = file.exists();
                if (exist) {
                    /*if (FileType.ENTITY == fileType) {
                        return false;
                    } else if (FileType.OTHER == fileType) {
                        return true;
                    } else {
                        return false;
                    }*/
                }
                return true;
            }
        });
        // 如果模板引擎是 freemarker
        String mapperPath = "/templates/mapper.xml.ftl";
        String reqPath = "/templates/req.java.ftl";
        String saveReqPath = "/templates/saveReq.java.ftl";
        String viewPath = "/templates/view.java.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會(huì)被優(yōu)先輸出
        focList.add(new FileOutConfig(mapperPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴名秀、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化@骸!
                return projectPath + "/src/main/resources/mybatis/demo/" + tableInfo.getEntityName().replace("Entity","") + "Mapper" + StringPool.DOT_XML;
            }
        });
        focList.add(new FileOutConfig(reqPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 匕得, 如果你 Entity 設(shè)置了前后綴继榆、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化!汁掠!
                return projectPath + "/src/main/java/com/gsgx/project/demo/model/req/" + tableInfo.getEntityName().replace("Entity","") + "Req" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(saveReqPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 略吨, 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化?稼濉翠忠!
                return projectPath + "/src/main/java/com/gsgx/project/demo/model/req/" + tableInfo.getEntityName().replace("Entity","") + "SaveReq" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(viewPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴乞榨、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化;嘀当娱!
                return projectPath + "/src/main/java/com/gsgx/project/demo/model/view/" + tableInfo.getEntityName().replace("Entity","") + "View" + StringPool.DOT_JAVA;
            }
        });
        /*focList.add(new FileOutConfig(entityPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴政溃、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化V悍谩!
                return projectPath + "/src/main/java/com/gsgx/project/demo/model/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });*/

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        //指定自定義模板路徑董虱,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
        templateConfig.setEntity("templates/entity.java");
        templateConfig.setMapper("templates/mapper.java");
        templateConfig.setController("templates/controller.java");
        // templateConfig.setService();
        // templateConfig.setController();
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //數(shù)據(jù)庫(kù)表映射到實(shí)體的命名策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //數(shù)據(jù)庫(kù)表字段映射到實(shí)體的命名策略, 未指定按照 naming 執(zhí)行
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //字段前綴
        strategy.setFieldPrefix("R_","T_","D_","I_","N_");
        strategy.setInclude(scanner("表名扼鞋,多個(gè)英文逗號(hào)分割").split(","));
        //駝峰轉(zhuǎn)連字符
        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        //tablePrefix
        strategy.setTablePrefix("survey" + "_");
        //Boolean類(lèi)型字段是否移除is前綴
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        //邏輯刪除屬性名稱(chēng)
        strategy.setLogicDeleteFieldName("del");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}


4、配置模板

controller.java.ftl

package ${package.Controller};

import com.traffic.common.response.ResponseJson;
import org.springframework.validation.annotation.Validated;
import com.github.pagehelper.PageInfo;
import java.util.List;
import ${package.Entity}.${entity};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ${package.Service}.${table.serviceName};
import lombok.extern.slf4j.Slf4j;


/**
 * <p>
    * ${table.comment!} 前端控制器
    * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@RestController
@Slf4j
@RequestMapping("/${table.entityPath?replace("Entity", "")}")
public class ${table.controllerName} {

    @Autowired
    private ${table.serviceName} ${table.entityPath?replace("Entity", "")}Service;


    @GetMapping("/list")
    public ResponseJson list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
    List<${table.entityName?replace("Entity", "View")}> list = ${table.entityPath?replace("Entity", "Service")}.list(${table.entityPath?replace("Entity", "Req")});
        return ResponseJson.newResponseJson(list);
    }

    @GetMapping("/page")
    public ResponseJson page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
        PageInfo page = ${table.entityPath?replace("Entity", "Service")}.page(${table.entityPath?replace("Entity", "Req")});
        return ResponseJson.newResponseJson(page);
    }

    @GetMapping("/remove")
    public ResponseJson remove(@RequestParam("id") String id) {
        ${table.entityPath?replace("Entity", "Service")}.remove(id);
        return ResponseJson.newResponseJson();
    }

    @PostMapping("/save")
    public ResponseJson save(@RequestBody @Validated ${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")}) {
        String id = ${table.entityPath?replace("Entity", "Service")}.save(${table.entityPath?replace("Entity", "SaveReq")});
        return ResponseJson.newResponseJson(id);
    }

    @GetMapping("/get/{id}")
    public ResponseJson getById(@PathVariable("id") String id) {
        ${table.entityName?replace("Entity", "View")} ${table.entityPath?replace("Entity", "View")} = ${table.entityPath?replace("Entity", "Service")}.getById(id);
        return ResponseJson.newResponseJson(${table.entityPath?replace("Entity", "View")});
    }
}

entity.java.ftl

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>

/**
 * <p>
 * ${table.comment!} 對(duì)象
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
</#if>
<#if table.convert>
@TableName("${table.name}")
</#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>

    private static final long serialVersionUID = 1L;
<#-- ----------  BEGIN 字段循環(huán)遍歷  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.comment!?length gt 0>
    /**
     * ${field.comment}
     */
    </#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??>
    <#-- -----   存在字段填充設(shè)置   ----->
        <#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>
<#-- 樂(lè)觀鎖注解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
<#-- 邏輯刪除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循環(huán)遍歷  ---------->

<#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>
}

req.java.ftl

package ${package.Entity?replace("entity", "req")};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>

/**
 * <p>
    * ${table.comment!} 請(qǐng)求對(duì)象
    * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "Req")}  extends BaseReq {
</#if>

}

saveReq.java.ftl

package ${package.Entity?replace("entity", "req")};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>

/**
 * <p>
    * ${table.comment!} 對(duì)象
    * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "SaveReq")}{
</#if>

<#-- ----------  BEGIN 字段循環(huán)遍歷  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.comment!?length gt 0>
    /**
     * ${field.comment}
     */
    </#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??>
    <#-- -----   存在字段填充設(shè)置   ----->
        <#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>
<#-- 樂(lè)觀鎖注解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
<#-- 邏輯刪除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循環(huán)遍歷  ---------->

<#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>
}

view.java.ftl

package ${package.Entity?replace("entity", "view")};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>

/**
 * <p>
    * ${table.comment!} 對(duì)象
    * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "View")}  extends BaseView {
</#if>
<#-- ----------  BEGIN 字段循環(huán)遍歷  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.comment!?length gt 0>
    /**
     * ${field.comment}
     */
    </#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??>
    <#-- -----   存在字段填充設(shè)置   ----->
        <#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>
<#-- 樂(lè)觀鎖注解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
<#-- 邏輯刪除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循環(huán)遍歷  ---------->

<#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 java.util.List;
import com.github.pagehelper.Page;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface ${table.mapperName}  {


    List<${table.entityName}> selectAll(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});

    void delete(@Param("id") String id);

    ${table.entityName} getById(@Param("id") String id);

    void update(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});

    void insert(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});

    Page<${table.entityName}> selectPage(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});

}

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}">

    <!-- 通用設(shè)置 -->
<#if baseColumnList>
    <!-- 通用查詢(xún)列 -->
    <sql id="Base_Column_List">
        <#list table.commonFields as field>
            ${field.name},
        </#list>
        ${table.fieldNames}
    </sql>

    <!-- 通用條件列 -->
    <sql id="${entity}ByCondition">
    <#list table.commonFields as field><#--生成公共字段-->
        <if test="${field.propertyName}!=null and ${field.propertyName}!=''">
            AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
        </if>
    </#list>
    <#list table.fields as field>
        <#if !field.keyFlag><#--生成普通字段 -->
            <if test="${field.propertyName}!=null and ${field.propertyName}!=''">
                AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
            </if>
        </#if>
    </#list>
    </sql>

    <!-- 通用設(shè)置列 -->
    <sql id="${entity}SetColumns">
    <#list table.commonFields as field><#--生成公共字段-->
        <if test="${field.propertyName}!=null and ${field.propertyName}!=''">
            ${field.name} = ${r"#{"}${field.propertyName}${r"}"},
        </if>
    </#list>
    <#list table.fields as field>
        <#if !field.keyFlag><#--生成普通字段 -->
            <if test="${field.propertyName}!=null and ${field.propertyName}!=''">
                ${field.name} = ${r"#{"}${field.propertyName}${r"}"},
            </if>
        </#if>
    </#list>
    </sql>
</#if>

<#if baseResultMap>
    <!-- 通用查詢(xún)映射結(jié)果 -->
    <resultMap id="${entity}Map" 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>

    <!-- 查詢(xún)表${table.name}所有信息 -->
    <select id="findAll" resultMap="${entity}Map">
        SELECT
        <include refid="Base_Column_List"/>
        FROM ${table.name}
    </select>

<#list table.fields as field>
    <#if field.keyFlag>
    <!-- 根據(jù)主鍵${field.propertyName}查詢(xún)表${table.name}信息 -->
    <select id="findBy${field.propertyName}" resultMap="${entity}Map">
        SELECT
        <include refid="Base_Column_List"/>
        FROM ${table.name}
        WHERE ${field.name}=${r"#{"}${field.propertyName}${r"}"}
    </select>
    </#if>
</#list>

    <!-- 根據(jù)條件查詢(xún)表${table.name}信息 -->
    <select id="findByCondition" resultMap="${entity}Map">
        SELECT
        <include refid="Base_Column_List"/>
        FROM ${table.name}
        WHERE 1=1
        <include refid="${entity}ByCondition" />
    </select>

<#list table.fields as field>
    <#if field.keyFlag>
    <!-- 根據(jù)主鍵${field.propertyName}刪除表${table.name}信息 -->
    <delete id="deleteBy${field.propertyName}">
        DELETE FROM
        ${table.name}
        WHERE ${field.name}=${r"#{"}${field.propertyName}${r"}"}
    </delete>
    </#if>
</#list>

<#list table.fields as field>
    <#if field.keyFlag>
    <!-- 根據(jù)主鍵${field.propertyName}更新表${table.name}信息 -->
    <update id="updateBy${field.propertyName}" parameterType="${package.Entity}.${entity}">
        UPDATE ${table.name}
        <set>
            <include refid="${entity}SetColumns"/>
        </set>
        WHERE
        <#list table.fields as field><#if field.keyFlag>${field.name}=${r"#{"}${field.propertyName}${r"}"}</#if></#list>
    </update>
    </#if>
</#list>

<#list table.fields as field>
    <#if field.keyFlag>
    <!-- 新增表${table.name}信息 -->
    <insert id="add">
        INSERT INTO ${table.name} (
        <#list table.fields as field>
            <#if field_index gt 0>,</#if>${field.name}
        </#list>
        ) VALUES (
        <#list table.fields as field>
            <#if field_index gt 0>,</#if>${r"#{"}${field.propertyName}${r"}"}
        </#list>
        )
    </insert>
    </#if>
</#list>
</mapper>

service.java.ftl

package ${package.Service};

import ${package.Entity}.${entity};
import java.util.List;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;

import java.util.List;

public interface ${table.serviceName} {

    List<${table.entityName?replace("Entity", "View")}> list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});

    PageInfo page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});

    void remove(String id);

    String save(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});

    ${table.entityName?replace("Entity", "View")} getById(String id);

}

serviceImpl.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import java.util.List;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Service
public class ${table.serviceImplName}  implements ${table.serviceName} {

    @Autowired
    private ${table.mapperName} ${table.entityPath?replace("Entity", "Mapper")};


    @Override
    public List<${table.entityName?replace("Entity", "View")}> list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
        List<${table.entityName?replace("Entity", "View")}> ${table.entityPath?replace("Entity", "View")}s = new BeanUtilsBean2TryCatch<${table.entityName}, ${table.entityName?replace("Entity", "View")}>().copyPropertiesList(${table.entityPath?replace("Entity", "Mapper")}.selectAll(${table.entityPath?replace("Entity", "Req")}), ${table.entityName?replace("Entity", "View")}.class);
        return ${table.entityPath?replace("Entity", "View")}s;
    }
    @Override
    public PageInfo page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
        Page page = ${table.entityPath?replace("Entity", "Mapper")}.selectPage(${table.entityPath?replace("Entity", "Req")});
        PageInfo pageInfo = new PageInfo(page);
        pageInfo.setList(new BeanUtilsBean2TryCatch<${table.entityName},${table.entityName?replace("Entity", "View")}>().copyPropertiesList(page.getResult(), ${table.entityName?replace("Entity", "View")}.class));
        return pageInfo;
    }

    @Override
    public String save(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")}) {
        //  判斷數(shù)據(jù)庫(kù)中是否有這條記錄
        ${table.entityName} ${table.entityPath} = ${table.entityPath?replace("Entity", "Mapper")}.getById(${table.entityPath?replace("Entity", "SaveReq")}.getId());
        if (${table.entityPath} != null) {
            ${table.entityPath?replace("Entity", "Mapper")}.update(${table.entityPath?replace("Entity", "SaveReq")});
        }else{
            ${table.entityPath?replace("Entity", "Mapper")}.insert(${table.entityPath?replace("Entity", "SaveReq")});
        }
        return ${table.entityPath?replace("Entity", "SaveReq")}.getId();

    }
    @Override
    public void remove(String ${table.entityPath?replace("Entity", "")}Id) {
        ${table.entityPath?replace("Entity", "Mapper")}.delete(${table.entityPath?replace("Entity", "")}Id);
    }

    @Override
    public ${table.entityName?replace("Entity", "View")} getById(String ${table.entityPath?replace("Entity", "")}Id) {
        ${table.entityName} ${table.entityPath} = ${table.entityPath?replace("Entity", "Mapper")}.getById(${table.entityPath?replace("Entity", "")}Id);
        return BeanUtilsBean2TryCatch.copyProperties(${table.entityPath}, ${table.entityName?replace("Entity", "View")}.class);
    }
}

5愤诱、執(zhí)行結(jié)果

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末云头,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子淫半,更是在濱河造成了極大的恐慌溃槐,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,376評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件科吭,死亡現(xiàn)場(chǎng)離奇詭異昏滴,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)对人,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén)谣殊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人牺弄,你說(shuō)我怎么就攤上這事姻几。” “怎么了势告?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,966評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵蛇捌,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我咱台,道長(zhǎng)络拌,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,432評(píng)論 1 283
  • 正文 為了忘掉前任回溺,我火速辦了婚禮春贸,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘馅而。我一直安慰自己祥诽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,519評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布瓮恭。 她就那樣靜靜地躺著雄坪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪屯蹦。 梳的紋絲不亂的頭發(fā)上维哈,一...
    開(kāi)封第一講書(shū)人閱讀 49,792評(píng)論 1 290
  • 那天绳姨,我揣著相機(jī)與錄音,去河邊找鬼阔挠。 笑死飘庄,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的购撼。 我是一名探鬼主播跪削,決...
    沈念sama閱讀 38,933評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼迂求!你這毒婦竟也來(lái)了碾盐?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,701評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤揩局,失蹤者是張志新(化名)和其女友劉穎毫玖,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體凌盯,經(jīng)...
    沈念sama閱讀 44,143評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡付枫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,488評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了驰怎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片阐滩。...
    茶點(diǎn)故事閱讀 38,626評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖砸西,靈堂內(nèi)的尸體忽然破棺而出叶眉,到底是詐尸還是另有隱情址儒,我是刑警寧澤芹枷,帶...
    沈念sama閱讀 34,292評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站莲趣,受9級(jí)特大地震影響鸳慈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜喧伞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,896評(píng)論 3 313
  • 文/蒙蒙 一走芋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧潘鲫,春花似錦翁逞、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,742評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至浊竟,卻和暖如春怨喘,著一層夾襖步出監(jiān)牢的瞬間津畸,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工必怜, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肉拓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓梳庆,卻偏偏與公主長(zhǎng)得像暖途,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子膏执,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,494評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容