Mybatis-Plus 代码生成器

1、创建表sys_units_dict

image.png

2、pom文件配置

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.3.2
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.3.2
        
        
        
            org.freemarker
            freemarker
            2.3.30
        
        
            org.projectlombok
            lombok
            1.18.8
        
        
        
            org.apache.commons
            commons-lang3
            3.9
        

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 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;


/**
 * 

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

* * @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};

<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


/**
 * 

* ${table.comment!} 对象 *

* * @author ${author} * @since ${date} */ <#if entityLombokModel> @Data <#if table.convert> @TableName("${table.name}") <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity} implements Serializable { private static final long serialVersionUID = 1L; <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> <#if field.comment!?length gt 0> /** * ${field.comment} */ <#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}") <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) <#elseif field.convert> @TableField("${field.name}") <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @TableLogic private ${field.propertyType} ${field.propertyName}; <#------------ END 字段循环遍历 ----------> <#if !entityLombokModel> <#list table.fields as field> <#if field.propertyType == "boolean"> <#assign getprefix="is"/> <#else> <#assign getprefix="get"/> 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}) { this.${field.propertyName} = ${field.propertyName}; <#if entityBuilderModel> return this; } <#if entityColumnConstant> <#list table.fields as field> public static final String ${field.name?upper_case} = "${field.name}"; <#if activeRecord> @Override protected Serializable pkVal() { <#if keyPropertyName??> return this.${keyPropertyName}; <#else> return null; } <#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} + "}"; } }

req.java.ftl

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

<#list table.importPackages as pkg>
import ${pkg};

<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


/**
 * 

* ${table.comment!} 请求对象 *

* * @author ${author} * @since ${date} */ <#if entityLombokModel> @Data <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity?replace("Entity", "Req")} extends BaseReq { }

saveReq.java.ftl

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

<#list table.importPackages as pkg>
import ${pkg};

<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


/**
 * 

* ${table.comment!} 对象 *

* * @author ${author} * @since ${date} */ <#if entityLombokModel> @Data <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity?replace("Entity", "SaveReq")}{ <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> <#if field.comment!?length gt 0> /** * ${field.comment} */ <#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}") <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) <#elseif field.convert> @TableField("${field.name}") <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @TableLogic private ${field.propertyType} ${field.propertyName}; <#------------ END 字段循环遍历 ----------> <#if !entityLombokModel> <#list table.fields as field> <#if field.propertyType == "boolean"> <#assign getprefix="is"/> <#else> <#assign getprefix="get"/> 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}) { this.${field.propertyName} = ${field.propertyName}; <#if entityBuilderModel> return this; } <#if entityColumnConstant> <#list table.fields as field> public static final String ${field.name?upper_case} = "${field.name}"; <#if activeRecord> @Override protected Serializable pkVal() { <#if keyPropertyName??> return this.${keyPropertyName}; <#else> return null; } <#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} + "}"; } }

view.java.ftl

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

<#list table.importPackages as pkg>
import ${pkg};

<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


/**
 * 

* ${table.comment!} 对象 *

* * @author ${author} * @since ${date} */ <#if entityLombokModel> @Data <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity?replace("Entity", "View")} extends BaseView { <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> <#if field.comment!?length gt 0> /** * ${field.comment} */ <#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}") <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) <#elseif field.convert> @TableField("${field.name}") <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @TableLogic private ${field.propertyType} ${field.propertyName}; <#------------ END 字段循环遍历 ----------> <#if !entityLombokModel> <#list table.fields as field> <#if field.propertyType == "boolean"> <#assign getprefix="is"/> <#else> <#assign getprefix="get"/> 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}) { this.${field.propertyName} = ${field.propertyName}; <#if entityBuilderModel> return this; } <#if entityColumnConstant> <#list table.fields as field> public static final String ${field.name?upper_case} = "${field.name}"; <#if activeRecord> @Override protected Serializable pkVal() { <#if keyPropertyName??> return this.${keyPropertyName}; <#else> return null; } <#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} + "}"; } }

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





    
<#if baseColumnList>
    
    
        <#list table.commonFields as field>
            ${field.name},
        
        ${table.fieldNames}
    

    
    
    <#list table.commonFields as field><#--生成公共字段-->
        
            AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
        
    
    <#list table.fields as field>
        <#if !field.keyFlag><#--生成普通字段 -->
            
                AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
            
        
    
    

    
    
    <#list table.commonFields as field><#--生成公共字段-->
        
            ${field.name} = ${r"#{"}${field.propertyName}${r"}"},
        
    
    <#list table.fields as field>
        <#if !field.keyFlag><#--生成普通字段 -->
            
                ${field.name} = ${r"#{"}${field.propertyName}${r"}"},
            
        
    
    


<#if baseResultMap>
    
    
    <#list table.fields as field>
        <#if field.keyFlag><#--生成主键排在第一位-->
            
        
    
    <#list table.commonFields as field><#--生成公共字段 -->
        
    
    <#list table.fields as field>
        <#if !field.keyFlag><#--生成普通字段 -->
            
        
    
    


    
    

<#list table.fields as field>
    <#if field.keyFlag>
    
    
    


    
    

<#list table.fields as field>
    <#if field.keyFlag>
    
    
        DELETE FROM
        ${table.name}
        WHERE ${field.name}=${r"#{"}${field.propertyName}${r"}"}
    
    


<#list table.fields as field>
    <#if field.keyFlag>
    
    
        UPDATE ${table.name}
        
            
        
        WHERE
        <#list table.fields as field><#if field.keyFlag>${field.name}=${r"#{"}${field.propertyName}${r"}"}
    
    


<#list table.fields as field>
    <#if field.keyFlag>
    
    
        INSERT INTO ${table.name} (
        <#list table.fields as field>
            <#if field_index gt 0>,${field.name}
        
        ) VALUES (
        <#list table.fields as field>
            <#if field_index gt 0>,${r"#{"}${field.propertyName}${r"}"}
        
        )
    
    


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

你可能感兴趣的:(Mybatis-Plus 代码生成器)