(七)mybatis-plus之generator(ftl模板生成:lombok swagger2 controloer的crud)

springboot 集成swagger2的访问地址是:http://localhost:端口号/swagger-ui.html

关于如何集成swagger2这里就不介绍了,前面发过了。这里主要介绍一下mybatis-plus使用ftl如何自动生成代码

关于lombok,需要idea提前安装一个插件的,不会的可以自行百度

关于pom.xml配置,这里我采用的版本有些新,如果有问题请留言,其他的版本,在前面有介绍,这里只做增量处理

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>    

generator代码(注:具体路径请根据实际项目进行修改)

public class MpGenerator {
    /**
     * 参数配置
     * @param args
     */
    //作者
    private static final String AUTHOR = "xx";
    //表名前缀
    //private static final String[] TABLEPREFIX = {"t_"};
    private static final String[] TABLEPREFIX = {""};
    //表名
    private static final String[] TABLENAMES = {"accound"};
    //包名称
    private static final String PACKAGENAME = "com.cn.wj";
    //用户名
    private static final String USERNAME = "root";
    //密码
    private static final String PASSWORD = "123456";
    //数据库url
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";

    public static void main(String[] args)
    {
        AutoGenerator mpg = new AutoGenerator();

        /**
         * 全局变量配置
         */
        GlobalConfig gc = new GlobalConfig();
        // 当前项目
        final String projectPath = System.getProperty("user.dir");
        // 输出路径
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setFileOverride(true);
        gc.setAuthor("cyy");
        gc.setOpen(false);
        gc.setSwagger2(true);
        gc.setBaseResultMap(true);
        gc.setDateType(DateType.TIME_PACK);
        gc.setBaseColumnList(true);

        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        /**
         * 数据源配置
         */
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        mpg.setDataSource(dsc);

        /**
         * 数据库表配置
         */
        StrategyConfig strategy = new StrategyConfig();

        strategy.setTablePrefix(TABLEPREFIX)
                .setRestControllerStyle(true)
                .setEntityLombokModel(true);

        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setCapitalMode(true);
        strategy.setInclude(TABLENAMES);
        mpg.setStrategy(strategy);

        /**
         * 包配置
         */
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.cn.wj");
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        mpg.setPackageInfo(pc);

        /**
         * 自定义配置
         */
        InjectionConfig cfg = new InjectionConfig()
        {
            @Override
            public void initMap()
            {
            }
        };

        /**
         * 将xml生成到resource下面
         */
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List focList = new ArrayList();

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath)
        {
            @Override
            public String outputFile(TableInfo tableInfo)
            {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

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

        templateConfig.setEntity("templates/entity");
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
        // /templates/entity.java 模板路径配置,默认再templates
        templateConfig.setController("templates/controller");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        /**
         * 模板引擎
         */
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
    }
}

ftl模板(这里只写了entity,controller)因为采用的是mybatis-plus的,service是不需要写代码的

controller.ftl

package ${package.Controller};


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

<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.cn.wj.common.util.ResponseDTO;
import  ${package.Service}.${table.serviceName};
import  ${package.Entity}.${table.entityName};
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>

/**
 * <p>
 *  ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@Slf4j
@Api(value = "${table.name}CRUD接口")
@RequestMapping("<#if package.ModuleName??>${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

    private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    private ${table.serviceName} ${table.name}Service;

    @ApiOperation(value = "获取${table.name}列表",notes="")
    @GetMapping("/")
    public List<${table.entityName}> ${table.name}List() throws Exception {
        List<${table.entityName}> ${table.name}List = ${table.name}Service.list();
        return ${table.name}List;
    }

    @ApiOperation(value = "修改${table.name}",notes="根据id修改${table.name}")
    @ApiImplicitParam(name = "${table.name}", value = "${table.name}实体", required = true, dataType = "Student")
    @PutMapping("/")
    public ResponseDTO<Boolean> ${table.name}Update(@RequestBody  ${table.entityName} ${table.name}) throws Exception {
        Boolean flag = ${table.name}Service.updateById(${table.name});
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }

    @ApiOperation(value = "删除${table.name}",notes="根据id删除${table.name}")
    @ApiImplicitParam(name = "id", value = "${table.name}id", required = true, dataType = "<#list table.fields as field><#if field.keyFlag == true>${field.columnType?lower_case?cap_first}</#if></#list>")
    @DeleteMapping("/{id}")
    public ResponseDTO<Boolean> ${table.name}Delete(@PathVariable <#list table.fields as field><#if field.keyFlag == true>${field.columnType?lower_case?cap_first}</#if></#list> id) throws Exception {
        Boolean flag = ${table.name}Service.removeById(id);
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }

    @ApiOperation(value = "添加${table.name}",notes="新增一条${table.name}")
    @ApiImplicitParam(name = "${table.name}", value = "${table.name}实体", required = true, dataType = "${table.name}")
    @PostMapping("")
    public ResponseDTO<Boolean> ${table.name}Insert(@RequestBody  ${table.entityName} ${table.name}) throws Exception {
        Boolean flag = ${table.name}Service.save(${table.name});
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }
}
</#if>

entity.ftl

package ${package.Entity};

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

/**
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
<#if chainModel>
@Accessors(chain = true)
</#if>
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>

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

    <#if field.comment!?length gt 0>
    <#if swagger2>
    @ApiModelProperty(value = "${field.comment}")
    <#else>
        /**
        * ${field.comment}
        */
    </#if>
    </#if>
    <#if field.keyFlag>
    <#-- 主键 -->
    <#if field.keyIdentityFlag>
    @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
    <#elseif idType??>
    @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
    <#elseif field.convert>
    @TableId("${field.annotationColumnName}")
    </#if>
    <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
    <#if field.convert>
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
    <#else>
    @TableField(fill = FieldFill.${field.fill})
    </#if>
    <#elseif field.convert>
    @TableField("${field.annotationColumnName}")
    </#if>
<#-- 乐观锁注解 -->
    <#if (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 chainModel>
            public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
            public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if chainModel>
            return this;
        </#if>
        }
    </#list>
</#if>

<#if entityColumnConstant>
    <#list table.fields as field>
        public static final String ${field.name?upper_case} = "${field.name}";
    </#list>
</#if>
<#if activeRecord>
    @Override
    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>
}

以上两个ftl的存放路径

生成的文件

entity

package com.cn.wj.entity;

import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableName;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author cyy
 * @since 2020-12-11
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("accound")
@ApiModel(value="Accound对象", description="")
public class Accound implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "UUID")
    private String id;

    @ApiModelProperty(value = "用户ID")
    private String userId;

    @ApiModelProperty(value = "记录时间")
    private LocalDateTime recordTime;

    @ApiModelProperty(value = "账目名称")
    private String name;

    @ApiModelProperty(value = "收入")
    private BigDecimal income;

    @ApiModelProperty(value = "支出")
    private BigDecimal expenditure;

    @ApiModelProperty(value = "修改时间")
    private String modificationTime;

    @ApiModelProperty(value = "是否删除(0:已删除 1:未删除)")
    private Boolean isDel;

    @ApiModelProperty(value = "备注")
    private String remarks;

    @ApiModelProperty(value = "支出类型(0-9)")
    private Integer expenditureType;


}

controller

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

import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.cn.wj.common.util.ResponseDTO;
import  com.cn.wj.service.AccoundService;
import  com.cn.wj.entity.Accound;

/**
 * <p>
 *   前端控制器
 * </p>
 *
 * @author cyy
 * @since 2020-12-11
 */
@RestController
@Slf4j
@Api(value = "accoundCRUD接口")
@RequestMapping("/accound")
public class AccoundController {

    private final Logger logger = LoggerFactory.getLogger(AccoundController.class);

    @Autowired
    private AccoundService accoundService;

    @ApiOperation(value = "获取accound列表",notes="")
    @GetMapping("/")
    public List<Accound> accoundList() throws Exception {
        List<Accound> accoundList = accoundService.list();
        return accoundList;
    }

    @ApiOperation(value = "修改accound",notes="根据id修改accound")
    @ApiImplicitParam(name = "accound", value = "accound实体", required = true, dataType = "Student")
    @PutMapping("/")
    public ResponseDTO<Boolean> accoundUpdate(@RequestBody  Accound accound) throws Exception {
        Boolean flag = accoundService.updateById(accound);
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }

    @ApiOperation(value = "删除accound",notes="根据id删除accound")
    @ApiImplicitParam(name = "id", value = "accoundid", required = true, dataType = "String")
    @DeleteMapping("/{id}")
    public ResponseDTO<Boolean> accoundDelete(@PathVariable String id) throws Exception {
        Boolean flag = accoundService.removeById(id);
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }

    @ApiOperation(value = "添加accound",notes="新增一条accound")
    @ApiImplicitParam(name = "accound", value = "accound实体", required = true, dataType = "accound")
    @PostMapping("")
    public ResponseDTO<Boolean> accoundInsert(@RequestBody  Accound accound) throws Exception {
        Boolean flag = accoundService.save(accound);
        return ResponseDTO.ok(Boolean.valueOf(flag));
    }
}

如果缺少什么或者有不懂的地方,欢迎留言沟通,需要原文件的可以留言

原文地址:https://www.cnblogs.com/changyuyao/p/14121022.html