Mybatis-Plus 代码生成器

1、创建表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>
        <!-- 扩展代码生成插件 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、新建生成器类(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 {


    /**
     * 读取控制台内容
     */
    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) {
        // 代码生成器
        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");
        //是否打开输出目录
        gc.setOpen(false);
        //是否覆盖已有文件
        gc.setFileOverride(true);
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        //service 命名方式
        gc.setServiceName("%sService");
        //entity 命名方式
        gc.setEntityName("%sEntity");

        mpg.setGlobalConfig(gc);

        // 数据源配置
        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) {
                //如果不存在,创建;如果存在,判断是否是entity.java:如果是,创建(覆盖);否则,不创建。
                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<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(mapperPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                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 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                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 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                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 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                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 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                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, 会根据使用的模板引擎自动识别
        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();
        //数据库表映射到实体的命名策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //字段前缀
        strategy.setFieldPrefix("R_","T_","D_","I_","N_");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        //驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        //tablePrefix
        strategy.setTablePrefix("survey" + "_");
        //Boolean类型字段是否移除is前缀
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        //逻辑删除属性名称
        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!} 对象
 * </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 字段循环遍历  ---------->
<#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??>
    <#-- -----   存在字段填充设置   ----->
        <#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>
}

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!} 请求对象
    * </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!} 对象
    * </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 字段循环遍历  ---------->
<#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??>
    <#-- -----   存在字段填充设置   ----->
        <#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>
}

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!} 对象
    * </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 字段循环遍历  ---------->
<#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??>
    <#-- -----   存在字段填充设置   ----->
        <#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 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}">

    <!-- 通用设置 -->
<#if baseColumnList>
    <!-- 通用查询列 -->
    <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>

    <!-- 通用设置列 -->
    <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>
    <!-- 通用查询映射结果 -->
    <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>

    <!-- 查询表${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>
    <!-- 根据主键${field.propertyName}查询表${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>

    <!-- 根据条件查询表${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>
    <!-- 根据主键${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>
    <!-- 根据主键${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")}) {
        //  判断数据库中是否有这条记录
        ${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、执行结果

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容