(七)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));
    }
}

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM