1. 程式人生 > 實用技巧 >MybatisPlus根據模板生成器程式碼

MybatisPlus根據模板生成器程式碼

導讀  

  網上的程式碼生成器,都不是自己想要的,今天下午研究了下,可以使用mybatisplus自定義模板,根據模板生成相應的程式碼,可以根據需求,改造相應模板即可。程式碼已上傳github/百度雲。

專案結構

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository
--> </parent> <groupId>con.cyb</groupId> <artifactId>ybchen_mybatis_builder</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ybchen_mybatis_builder</name> <description>mybatis程式碼生成器</description> <properties
> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring boot --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- web依賴,包含servlet,內建tomcat等 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis-plus依賴, 可以代替mybatis --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!-- MyBatis-Plus 從 3.0.3 之後移除了程式碼生成器與模板引擎的預設依賴,需要手動新增相關依賴--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.1.1</version> </dependency> <!-- Freemarker模板引擎 --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

controller.java.ftl

package ${package.Controller};

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import ${package.Service}.${table.serviceName};

@RestController
@RequestMapping("/${table.entityPath}")
public class ${table.controllerName} {

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

}

entity.java.ftl

package ${package.Entity};

import java.io.Serializable;
import java.util.Date;
<#list table.importPackages as pkg>
<#if pkg == "java.util.Date">
import ${pkg};
</#if>
</#list>

/**
 * ${table.name} : ${table.comment!}
 */
public class ${entity}  implements Serializable {

    private static final long serialVersionUID = 1L;
<#-- ----------  屬性私有化  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.keyFlag>
    <#-- 主鍵 -->
    /**
     * 主鍵 : ${field.name},  ${field.comment!}
     */
    <#-- 普通欄位 -->
    <#elseif !field.keyFlag>
    /**
     * ${field.name},  ${field.comment!}
     */
    </#if>
<#-- 樂觀鎖註解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
<#-- 邏輯刪除註解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    <#if field.propertyType == "LocalDateTime">
        private Date ${field.propertyName};
    </#if>
    <#if field.propertyType != "LocalDateTime">
        private ${field.propertyType} ${field.propertyName};
    </#if>
</#list>

<#------------  建構函式   ----------- -->
    public ${entity}(<#list table.fields as field><#if field.propertyType == "LocalDateTime">Date ${field.propertyName}</#if><#if field.propertyType != "LocalDateTime">${field.propertyType} ${field.propertyName}</#if><#sep>,</#list>){
        <#list table.fields as field>
            this.${field.propertyName} = ${field.propertyName};
        </#list>
    }
    
    public ${entity}(){
    }

<#------------  getter.setter封裝  ---------->
<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
    public <#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }
        <#if entityBuilderModel>
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
    public void set${field.capitalName}(<#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${field.propertyName}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if entityBuilderModel>
        return this;
        </#if>
    }
    </#list>
</#if>

<#-------------  重寫toString()  ----------------->
<#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.xml.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface ${table.mapperName}{
    
     /**
      *  查詢表${table.name}所有資訊
      */
     List<${entity}> findAll${entity}();
      
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根據主鍵${field.propertyName}查詢表${table.name}資訊
      *  @param ${field.propertyName}
      */
     ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
    </#list>

    /**
    *  根據條件查詢表${table.name}資訊
    *  @param ${table.entityPath}
    */
    List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath});

    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根據主鍵${field.propertyName}查詢表${table.name}資訊
      *  @param ${field.propertyName}
      */
     Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
    </#list>
    
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根據主鍵${field.propertyName}更新表${table.name}資訊
      *  @param ${table.entityPath}
      */
     Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath});
    </#if>
    </#list>
    
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  新增表${table.name}資訊
      *  @param ${table.entityPath}
      */
     Integer add${entity}(${entity} ${table.entityPath});
    </#if>
    </#list>
    
}

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${entity}" 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="find${entity}By${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="find${entity}ByCondition" 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="delete${entity}By${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="update${entity}By${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${entity}">
        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 org.apache.ibatis.annotations.Param;

import java.util.List;

public interface ${table.serviceName}{

    /**
    *  查詢表${table.name}所有資訊
    */
    List<${entity}> findAll${entity}();

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}查詢表${table.name}資訊
    *  @param ${field.propertyName}
    */
    ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>

    /**
    *  根據條件查詢表${table.name}資訊
    *  @param ${table.entityPath}
    */
    List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath});

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}查詢表${table.name}資訊
    *  @param ${field.propertyName}
    */
    Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}更新表${table.name}資訊
    *  @param ${table.entityPath}
    */
    Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath});
</#if>
</#list>

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  新增表${table.name}資訊
    *  @param ${table.entityPath}
    */
    Integer add${entity}(${entity} ${table.entityPath});
</#if>
</#list>
}

serviceImpl.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
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}Mapper;

    /**
    *  查詢表${table.name}所有資訊
    */
    @Override
    public List<${entity}> findAll${entity}() { return ${table.entityPath}Mapper.findAll${entity}();}

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}查詢表${table.name}資訊
    *  @param ${field.propertyName}
    */
    @Override
    public ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) { return ${table.entityPath}Mapper.find${entity}By${field.propertyName}(${field.propertyName});}
</#if>
</#list>

    /**
    *  根據條件查詢表${table.name}資訊
    *  @param ${table.entityPath}
    */
    @Override
    public List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.find${entity}ByCondition(${table.entityPath});}

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}查詢表${table.name}資訊
    *  @param ${field.propertyName}
    */
    @Override
    public Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) { return ${table.entityPath}Mapper.delete${entity}By${field.propertyName}(${field.propertyName});}
</#if>
</#list>

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  根據主鍵${field.propertyName}更新表${table.name}資訊
    *  @param ${table.entityPath}
    */
    @Override
    public Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.update${entity}By${field.propertyName}(${table.entityPath});}
</#if>
</#list>

<#list table.fields as field>
<#if field.keyFlag>
    /**
    *  新增表${table.name}資訊
    *  @param ${table.entityPath}
    */
    @Override
    public Integer add${entity}(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.add${entity}(${table.entityPath});}
</#if>
</#list>

}

Generator.java

package con.cyb.build;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:Generator
 * @Description:程式碼自動生成器
 * @Author:chenyb
 * @Date:2020/9/20 8:10 下午
 * @Versiion:1.0
 */
public class Generator {
    
    public static void main(String[] args) {
        // 生成地址 : // System.getProperty("user.dir") == 得到當前專案的實際地址
        String outputDir = System.getProperty("user.dir") + "/src/main/java";
//        String outputDir = "C://Users/VULCAN/Desktop/new";
        // 表名, 注意大小寫
        String[] tableNames = new String[]{"chapter"};
        // 資料庫地址
        String url = "jdbc:mysql://localhost:3306/online_ybclass?useUnicode=true&characterEncoding=utf8";
        // 使用者名稱
        String userName = "root";
        // 密碼
        String password = "root";
        // 父包路徑
        String parentPackage = "con.cyb";
        // 需要去掉的表名字首
        String prefixTable = "Test_";
        generate(outputDir, tableNames, url, userName, password, parentPackage, prefixTable);
    }
    
    /**
     * @param outputDir   生成地址
     * @param tableNames  表名
     * @param url            資料庫地址
     * @param userName       使用者名稱
     * @param password    密碼
     * @param parentPackage  父包路徑
     * @param prefixTable  需要去掉的表名字首
     */
    public static void generate(String outputDir, String[] tableNames, String url, String userName,
            String password, String parentPackage, String prefixTable) {
        // ===============  全域性配置  ==================
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outputDir)
            .setActiveRecord(true)                                // 是否支援 AR, 實體類只需繼承 Model 類即可進行強大的 CRUD 操作
            .setAuthor("GrassPrince")                             // 設定作者名字
            .setFileOverride(true)                                 // 檔案覆蓋(全新檔案)
            .setIdType(IdType.AUTO)                                // 主鍵策略
            .setBaseResultMap(true)                             // SQL 對映檔案
            .setBaseColumnList(true)                            // SQL 片段
            .setServiceName("%sService")                        // service的名字
            .setOpen(false);
        
        // =================  資料來源配置   ===============
        DataSourceConfig dsc = new DataSourceConfig();
            dsc.setDbType(DbType.MYSQL)
             .setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUrl(url)
           .setUsername(userName)
           .setPassword(password);
        
        // =================  包配置  ===================
         PackageConfig pc = new PackageConfig();
         pc.setParent(parentPackage)                            // 配置父包路徑
//           .setModuleName("base")                                // 配置業務包路徑
           .setMapper("mapper")
           .setEntity("entity")
           .setService("service")
           //.setServiceImpl("service.impl");                     // 會自動生成 impl,可以不設定
           .setController("controller");
         
       // ==================  自定義配置  ================= 
         InjectionConfig cfg = new InjectionConfig() {
             @Override
             public void initMap() {
                 // to do nothing
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
         // 調整 xml 生成目錄演示
         focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // 自定義輸入檔名稱
                 return System.getProperty("user.dir") + "/src/main/resources/mybatis/"
                         + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
             }
         });
         cfg.setFileOutConfigList(focList);
         
         // ===================  策略配置  ================== 
         StrategyConfig strategy = new StrategyConfig();
         strategy.setNaming(NamingStrategy.underline_to_camel)                    // 表名命名:  underline_to_camel 底線變駝峰
                 .setColumnNaming(NamingStrategy.underline_to_camel)            // 欄位命名: underline_to_camel 底線變駝峰
                 .setInclude(tableNames)                                        // 需要生成的 表名
                 .setCapitalMode(true)                                            // 全域性大寫命名 ORACLE 注意 
                 .setTablePrefix(prefixTable)                                    // 去掉 表的字首
//                 .setFieldPrefix(pc.getModuleName() + "_")                    // 去掉欄位字首
//                 .setSuperEntityClass("com.maoxs.pojo")                        // 繼承類
//                 .setSuperControllerClass("com.maoxs.controller")                // 繼承類
//                 .setSuperEntityColumns("id")                                 // 設定超級超級列
//                 .setEntityLombokModel(true)                                    // 是否加入lombok
                 .setControllerMappingHyphenStyle(true);                        // 設定controller對映聯字元
       
         // ==================  自定義模板配置: 預設配置位置 mybatis-plus/src/main/resources/templates  ======================
         // 放置自己專案的 src/main/resources/templates 目錄下, 預設名稱一下可以不配置,也可以自定義模板名稱
         TemplateConfig tc = new TemplateConfig();
         tc.setXml(null)                                                        // 設定生成xml的模板
           .setEntity("/templates/entity.java")                                // 設定生成entity的模板
           .setMapper("/templates/mapper.java")                                // 設定生成mapper的模板
           .setController("/templates/controller.java")                       // 設定生成service的模板
           .setService("/templates/service.java")                            // 設定生成serviceImpl的模板
           .setServiceImpl("/templates/serviceImpl.java");                    // 設定生成controller的模板
         
         // ====================  生成配置  =================== 
         AutoGenerator mpg = new AutoGenerator();
         mpg.setCfg(cfg)
                 .setTemplate(tc)
                 .setGlobalConfig(gc)
                 .setDataSource(dsc)
                 .setPackageInfo(pc)
                 .setStrategy(strategy)
                 .setTemplateEngine(new FreemarkerTemplateEngine());            // 選擇 freemarker引擎,注意 pom 依賴必須有!
         mpg.execute();
    }

}

演示

下載

github

https://github.com/543210188/MybatisBuilder

百度雲盤

連結: https://pan.baidu.com/s/1a83ronSBhRisQ-U8HkTq_g  密碼: 7kar