Mybatis plus Generator 自動生成代碼

1. 官方文檔

2.使用的版本

Mybatis-plus 3.3.1 

Mybatis-plus-generator 3.3.1

Freemarker 2.3.30

3. pom依賴

        <!-- 2、MyBatis-Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <!--代碼生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1</version>
        </dependency>

       <!--使用freemark模板引擎-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

4. 生成器代碼

 package com.example.open.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Date: 2020/5/20
 * Time: 9:13
 *
 * @author wcb
 * Description: mybatis plus 代碼生成器
 */
public class MybatisPlusGenerator {

    /**
     * <p>
     * 讀取控制臺內(nèi)容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(("請輸入" + tip + ":"));
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(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 + "/open-platform-portal-backend" + "/src/main/java");
        gc.setAuthor("wcb");
        //是否打開輸出的目錄
        gc.setOpen(false);
        //設(shè)置生成實體日期屬性的類型,我這里用的是util中的Date
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.ORACLE);
        dsc.setUrl("jdbc:oracle:thin:@localhost:1521:open");
        dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

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

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


        //指定自定義模板路徑, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
        templateConfig.setEntity("templates/entityEngineTemplate/entity.java");
        templateConfig.setController("templates/entityEngineTemplate/controller.java");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);


        //實體共同繼承的基礎(chǔ)類, 里面抽取了共同的一些屬性
        strategy.setSuperEntityClass("com.example.open.entity.BaseEntity");
        // 寫于父類中的公共字段,一下為生成的實體所忽略的字段
        strategy.setSuperEntityColumns("ID", "CREATE_TIME", "MODIFY_TIME", "DELETED");
        //邏輯刪除屬性名稱
        strategy.setLogicDeleteFieldName("DELETED");

        //是否使用lombok注解
        strategy.setEntityLombokModel(true);
        //是否定義輸出的實體類有builder模式的調(diào)用鏈
        strategy.setEntityBuilderModel(true);
        //是否生成字段注解:讀取表中的注釋
        strategy.setEntityTableFieldAnnotationEnable(true);


        //是否生成@RestController注解的controller
        strategy.setRestControllerStyle(true);
        // controller共同繼承的公共父類
        strategy.setSuperControllerClass("com.example.open.web.controller.BaseController");

        //駝峰轉(zhuǎn)連接字符- , 例如PlatformUser -->  platform-user
        //strategy.setControllerMappingHyphenStyle(true);

        //去除表名的前綴的固定生成實體
        strategy.setTablePrefix("tb_");

        //決定是否使用自定義的實體類命名策略,注意使用自定義命名實體的方式時,請不要批量處理
        String choose = scanner("是否使用自定義的實體類名稱(y/n)?");
        if (StringUtils.matches(choose, "y")) {
            strategy.setInclude(scanner("請輸入表名"));
            strategy.setNameConvert(new CustomNameConvert(strategy));

            //自定義注入屬性,在使用單個生成時,可以使用
            InjectionConfig injectionConfig = new InjectionConfig() {

                //自定義屬性注入:abc
                //在.ftl(或者是.vm)模板中吩案,通過${cfg.abc}獲取屬性
                @Override
                public void initMap() {
                    List<TableInfo> list = this.getConfig().getTableInfoList();
                    if (list != null && !list.isEmpty()) {
                        TableInfo info = list.get(0);
                        Map<String, Object> map = new HashMap<>();
                        map.put("serviceImplNamePath", info.getEntityPath() + "Service");
                        super.setMap(map);
                    }
                }
            };

            mpg.setCfg(injectionConfig);

        } else {
            strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        }
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

5.實現(xiàn)的NameConvert

/**
 * Created with IntelliJ IDEA.
 * Date: 2020/5/20
 * Time: 10:45
 *
 * @author wcb
 * Description:  自定義的表與實體轉(zhuǎn)換策略
 */
public class CustomNameConvert implements INameConvert {

    /**
     * 策略配置
     */
    private StrategyConfig strategyConfig;


    public CustomNameConvert(StrategyConfig strategyConfig) {
        this.strategyConfig = strategyConfig;
    }


    @Override
    public String entityNameConvert(TableInfo tableInfo) {
        return MybatisPlusGenerator.scanner("請輸入實體名稱,注意駝峰命名");
    }

    @Override
    public String propertyNameConvert(TableField field) {
        return processName(field.getName(), strategyConfig.getNaming());
    }


    /**
     * 處理字段名稱
     *
     * @return 根據(jù)策略返回處理后的名稱
     */
    private String processName(String name, NamingStrategy strategy) {
        return processName(name, strategy, strategyConfig.getFieldPrefix());
    }


    /**
     * 處理表/字段名稱
     *
     * @param name     ignore
     * @param strategy ignore
     * @param prefix   ignore
     * @return 根據(jù)策略返回處理后的名稱
     */
    private String processName(String name, NamingStrategy strategy, String[] prefix) {
        boolean removePrefix = false;
        if (prefix != null && prefix.length != 0) {
            removePrefix = true;
        }
        String propertyName;
        if (removePrefix) {
            if (strategy == NamingStrategy.underline_to_camel) {
                // 刪除前綴韭脊、下劃線轉(zhuǎn)駝峰
                propertyName = NamingStrategy.removePrefixAndCamel(name, prefix);
            } else {
                // 刪除前綴
                propertyName = NamingStrategy.removePrefix(name, prefix);
            }
        } else if (strategy == NamingStrategy.underline_to_camel) {
            // 下劃線轉(zhuǎn)駝峰
            propertyName = NamingStrategy.underlineToCamel(name);
        } else {
            // 不處理
            propertyName = name;
        }
        return propertyName;
    }
}

6. Entity.java.ftl(注意:需要放在resources目錄下,需要在templateConfig中指定路徑,ps:不要格式化模板代碼,不然產(chǎn)生的代碼縮進會變化)

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
import com.baomidou.mybatisplus.annotation.TableField;
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#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 superEntityClass??>
@EqualsAndHashCode(callSuper = true)
    <#else>
@EqualsAndHashCode(callSuper = false)
    </#if>
@Accessors(chain = true)
</#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 字段循環(huán)遍歷  ---------->
<#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>
    @TableField("${field.name}")
    </#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??>
    <#-- -----   存在字段填充設(shè)置   ----->
        <#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 字段循環(huán)遍歷  ---------->

<#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>
}


7. controller.java.ftl

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import com.zjca.open.util.ResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@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>

    @Autowired
    private ${table.serviceName} ${cfg.serviceImplNamePath};

    /**
     * 查詢封裝條件的結(jié)果集
     *
     * @param entity 查詢參數(shù)封裝對象,一般為實體vo,若是需要查詢?nèi)?條件都為空即可
     * @return 返回查詢結(jié)果集與組拼的響應(yīng)對象
     *
     */
    @GetMapping("list")
    <#if !restControllerStyle>
    @ResponseBody
    </#if>
    public Object list(@RequestBody ${entity} entity) {
        return new ResultWrapper<>(${cfg.serviceImplNamePath}.list(new QueryWrapper<>(entity)));
    }

    /**
     * 返回一個${table.comment}對象
     *
     * @param id 需要查詢的對象ID
     * @return 返回ID匹配的一條數(shù)據(jù)與組拼的響應(yīng)對象
     */
    <#if !restControllerStyle>
    @ResponseBody
    </#if>
    @GetMapping(value = "getOne/{id}", produces = "application/json;charset=utf-8")
    public Object get(@PathVariable String id) {
        return new ResultWrapper<>(${cfg.serviceImplNamePath}.getById(id));
    }

    /**
     * 新增${table.comment}對象
     *
     * @param entity 查詢參數(shù)封裝對象,一般為實體vo,若是需要查詢?nèi)?條件都為空即可
     * @return 返回插入結(jié)果(true或false)與組拼的響應(yīng)對象
     */
    @PostMapping("insert")
    <#if !restControllerStyle>
    @ResponseBody
    </#if>
    public Object insert(@RequestBody ${entity} entity) {
        return new ResultWrapper<>(${cfg.serviceImplNamePath}.save(entity));
    }


    /**
     * 更新一個${table.comment}對象
     *
     * @param entity 需要更新的${table.comment}對象
     * @return 返回操作結(jié)果(true或false)與組拼的響應(yīng)對象
     */
    <#if !restControllerStyle>
    @ResponseBody
    </#if>
    @PatchMapping(value = "update", produces = "application/json;charset=utf-8", consumes = "application/json;charset=utf-8")
    public Object update(@RequestBody ${entity} entity) {
        return new ResultWrapper<>(${cfg.serviceImplNamePath}.update(new QueryWrapper<>(entity)));
    }

    /**
     * 刪除一個${table.comment}對象
     *
     * @param id 需要對象的Id
     * @return 返回操作結(jié)果(true或false)與組拼的響應(yīng)對象
     */
    <#if !restControllerStyle>
    @ResponseBody
    </#if>
    @DeleteMapping(value = "delete/{id}", produces = "application/json;charset=utf-8")
    public Object delete(@PathVariable String id) {
        return new ResultWrapper<>(${cfg.serviceImplNamePath}.removeById(id));
    }

}
</#if>

8. 如果還有疑惑,請多看配置類

/*
 * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.baomidou.mybatisplus.generator.config;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.po.LikeTable;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * 策略配置項
 *
 * @author YangHu, tangguo, hubin
 * @since 2016/8/30
 */
@Data
@Accessors(chain = true)
public class StrategyConfig {
    /**
     * 是否大寫命名
     */
    private boolean isCapitalMode = false;
    /**
     * 是否跳過視圖
     */
    private boolean skipView = false;
    /**
     * 名稱轉(zhuǎn)換
     */
    private INameConvert nameConvert;
    /**
     * 數(shù)據(jù)庫表映射到實體的命名策略
     */
    private NamingStrategy naming = NamingStrategy.no_change;
    /**
     * 數(shù)據(jù)庫表字段映射到實體的命名策略
     * <p>未指定按照 naming 執(zhí)行</p>
     */
    private NamingStrategy columnNaming = null;
    /**
     * 表前綴
     */
    @Setter(AccessLevel.NONE)
    private String[] tablePrefix;
    /**
     * 字段前綴
     */
    @Setter(AccessLevel.NONE)
    private String[] fieldPrefix;
    /**
     * 自定義繼承的Entity類全稱,帶包名
     */
    @Setter(AccessLevel.NONE)
    private String superEntityClass;
    /**
     * 自定義基礎(chǔ)的Entity類,公共字段
     */
    @Setter(AccessLevel.NONE)
    private String[] superEntityColumns;
    /**
     * 自定義繼承的Mapper類全稱,帶包名
     */
    private String superMapperClass = ConstVal.SUPER_MAPPER_CLASS;
    /**
     * 自定義繼承的Service類全稱虑凛,帶包名
     */
    private String superServiceClass = ConstVal.SUPER_SERVICE_CLASS;
    /**
     * 自定義繼承的ServiceImpl類全稱,帶包名
     */
    private String superServiceImplClass = ConstVal.SUPER_SERVICE_IMPL_CLASS;
    /**
     * 自定義繼承的Controller類全稱软啼,帶包名
     */
    private String superControllerClass;
    /**
     * 需要包含的表名(與exclude二選一配置)
     * @since 3.3.0 正則匹配不再支持,請使用{@link #setLikeTable(LikeTable)}}
     */
    @Setter(AccessLevel.NONE)
    private String[] include = null;
    /**
     * 需要排除的表名
     * @since 3.3.0 正則匹配不再支持,請使用{@link #setNotLikeTable(LikeTable)}}
     */
    @Setter(AccessLevel.NONE)
    private String[] exclude = null;
    /**
     * 實體是否生成 serialVersionUID
     */
    private boolean entitySerialVersionUID = true;
    /**
     * 【實體】是否生成字段常量(默認 false)<br>
     * -----------------------------------<br>
     * public static final String ID = "test_id";
     */
    private boolean entityColumnConstant = false;
    /**
     * 【實體】是否為構(gòu)建者模型(默認 false)<br>
     * -----------------------------------<br>
     * public User setName(String name) { this.name = name; return this; }
     */
    private boolean entityBuilderModel = false;
    /**
     * 【實體】是否為lombok模型(默認 false)<br>
     * <a >document</a>
     */
    private boolean entityLombokModel = false;
    /**
     * Boolean類型字段是否移除is前綴(默認 false)<br>
     * 比如 : 數(shù)據(jù)庫字段名稱 : 'is_xxx',類型為 : tinyint. 在映射實體的時候則會去掉is,在實體類中映射最終結(jié)果為 xxx
     */
    private boolean entityBooleanColumnRemoveIsPrefix = false;
    /**
     * 生成 <code>@RestController</code> 控制器
     * <pre>
     *      <code>@Controller</code> -> <code>@RestController</code>
     * </pre>
     */
    private boolean restControllerStyle = false;
    /**
     * 駝峰轉(zhuǎn)連字符
     * <pre>
     *      <code>@RequestMapping("/managerUserActionHistory")</code> -> <code>@RequestMapping("/manager-user-action-history")</code>
     * </pre>
     */
    private boolean controllerMappingHyphenStyle = false;
    /**
     * 是否生成實體時桑谍,生成字段注解
     */
    private boolean entityTableFieldAnnotationEnable = false;
    /**
     * 樂觀鎖屬性名稱
     */
    private String versionFieldName;
    /**
     * 邏輯刪除屬性名稱
     */
    private String logicDeleteFieldName;
    /**
     * 表填充字段
     */
    private List<TableFill> tableFillList = null;
    /**
     * 啟用sql過濾
     * 語法不能支持使用sql過濾表的話,可以考慮關(guān)閉此開關(guān).
     * 目前所知微軟系需要關(guān)閉祸挪,其他數(shù)據(jù)庫等待反饋霉囚,sql可能要改動一下才能支持,沒數(shù)據(jù)庫環(huán)境搞,請手動關(guān)閉使用內(nèi)存過濾的方式盈罐。
     *
     * @since 3.3.1
     */
    private boolean enableSqlFilter = true;
    /**
     * 包含表名
     *
     * @since 3.3.0
     */
    private LikeTable likeTable;
    /**
     * 不包含表名
     *
     * @since 3.3.0
     */
    private LikeTable notLikeTable;

    /**
     * 大寫命名榜跌、字段符合大寫字母數(shù)字下劃線命名
     *
     * @param word 待判斷字符串
     */
    public boolean isCapitalModeNaming(String word) {
        return isCapitalMode && StringUtils.isCapitalMode(word);
    }

    /**
     * 表名稱包含指定前綴
     *
     * @param tableName 表名稱
     */
    public boolean containsTablePrefix(String tableName) {
        if (null != tableName) {
            String[] tps = getTablePrefix();
            if (null != tps) {
                return Arrays.stream(tps).anyMatch(tableName::contains);
            }
        }
        return false;
    }

    public NamingStrategy getColumnNaming() {
        if (null == columnNaming) {
            // 未指定以 naming 策略為準
            return naming;
        }
        return columnNaming;
    }

    public StrategyConfig setTablePrefix(String... tablePrefix) {
        this.tablePrefix = tablePrefix;
        return this;
    }

    public boolean includeSuperEntityColumns(String fieldName) {
        if (null != superEntityColumns) {
            // 公共字段判斷忽略大小寫【 部分數(shù)據(jù)庫大小寫不敏感 】
            return Arrays.stream(superEntityColumns).anyMatch(e -> e.equalsIgnoreCase(fieldName));
        }
        return false;
    }

    public StrategyConfig setSuperEntityColumns(String... superEntityColumns) {
        this.superEntityColumns = superEntityColumns;
        return this;
    }

    public StrategyConfig setInclude(String... include) {
        this.include = include;
        return this;
    }

    public StrategyConfig setExclude(String... exclude) {
        this.exclude = exclude;
        return this;
    }

    public StrategyConfig setFieldPrefix(String... fieldPrefixs) {
        this.fieldPrefix = fieldPrefixs;
        return this;
    }

    public StrategyConfig setSuperEntityClass(String superEntityClass) {
        this.superEntityClass = superEntityClass;
        return this;
    }


    /**
     * <p>
     * 設(shè)置實體父類,該設(shè)置自動識別公共字段<br/>
     * 屬性 superEntityColumns 改配置無需再次配置
     * </p>
     * <p>
     * 注意V逊唷钓葫!字段策略要在設(shè)置實體父類之前有效
     * </p>
     *
     * @param clazz 實體父類 Class
     * @return
     */
    public StrategyConfig setSuperEntityClass(Class<?> clazz) {
        return setSuperEntityClass(clazz, null);
    }

    /**
     * <p>
     * 設(shè)置實體父類,該設(shè)置自動識別公共字段<br/>
     * 屬性 superEntityColumns 改配置無需再次配置
     * </p>
     *
     * @param clazz        實體父類 Class
     * @param columnNaming 字段命名策略
     * @return
     */
    public StrategyConfig setSuperEntityClass(Class<?> clazz, NamingStrategy columnNaming) {
        if (null != columnNaming) {
            this.columnNaming = columnNaming;
        }
        this.superEntityClass = clazz.getName();
        convertSuperEntityColumns(clazz);
        return this;
    }

    public StrategyConfig setSuperControllerClass(Class<?> clazz) {
        this.superControllerClass = clazz.getName();
        return this;
    }

    public StrategyConfig setSuperControllerClass(String superControllerClass) {
        this.superControllerClass = superControllerClass;
        return this;
    }

    /**
     * <p>
     * 父類 Class 反射屬性轉(zhuǎn)換為公共字段
     * </p>
     *
     * @param clazz 實體父類 Class
     */
    protected void convertSuperEntityColumns(Class<?> clazz) {
        List<Field> fields = TableInfoHelper.getAllFields(clazz);
        this.superEntityColumns = fields.stream().map(field -> {
            if (null == columnNaming || columnNaming == NamingStrategy.no_change) {
                return field.getName();
            }
            return StringUtils.camelToUnderline(field.getName());
        }).distinct().toArray(String[]::new);
    }

    /**
     * @deprecated please use `setEntityTableFieldAnnotationEnable`
     */
    @Deprecated
    public StrategyConfig entityTableFieldAnnotationEnable(boolean isEnableAnnotation) {
        entityTableFieldAnnotationEnable = isEnableAnnotation;
        return this;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末票顾,一起剝皮案震驚了整個濱河市础浮,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌奠骄,老刑警劉巖豆同,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異含鳞,居然都是意外死亡影锈,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門蝉绷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸭廷,“玉大人,你說我怎么就攤上這事熔吗×敬玻” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵桅狠,是天一觀的道長讼载。 經(jīng)常有香客問我,道長中跌,這世上最難降的妖魔是什么咨堤? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮晒他,結(jié)果婚禮上吱型,老公的妹妹穿的比我還像新娘。我一直安慰自己陨仅,他們只是感情好津滞,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著灼伤,像睡著了一般触徐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上狐赡,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天撞鹉,我揣著相機與錄音,去河邊找鬼。 笑死鸟雏,一個胖子當著我的面吹牛享郊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播孝鹊,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼炊琉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了又活?” 一聲冷哼從身側(cè)響起苔咪,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎柳骄,沒想到半個月后团赏,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡耐薯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年舔清,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片可柿。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡鸠踪,死狀恐怖丙者,靈堂內(nèi)的尸體忽然破棺而出复斥,到底是詐尸還是另有隱情,我是刑警寧澤械媒,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布目锭,位于F島的核電站,受9級特大地震影響纷捞,放射性物質(zhì)發(fā)生泄漏痢虹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一主儡、第九天 我趴在偏房一處隱蔽的房頂上張望奖唯。 院中可真熱鬧,春花似錦糜值、人聲如沸丰捷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽病往。三九已至,卻和暖如春骄瓣,著一層夾襖步出監(jiān)牢的瞬間停巷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留畔勤,地道東北人蕾各。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像庆揪,于是被迫代替她去往敵國和親示损。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355