根据表结构生成controller,service,repository,domain的工具类

package com.mdgyl.tools.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.jxdinfo.hussar.support.mp.base.mapper.HussarMapper;
import lombok.extern.slf4j.Slf4j;

import java.sql.Types;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


@Slf4j
public class Main {

    public static void main(String[] args) {
        String url = "jdbc:mysql://10.0.7.52:3306/md_gyl_sourcing?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true";
        String name = "mdgyl";
        String password = "mdgyl@2024";
        String projectDir = "D:\\project\\gyl\\mdgylxt-tools\\code-generator";

        String javaFileOutputDir = projectDir + "src/main/java";
        String xmlFileOutputDir = projectDir + "src/main/resources/mapper";
        String parentPackage = "com.mdgyl.hussar.basic.supplier";

        String moduleName = "";
//        String subPackage = "authority";


//        List includes = Arrays.asList("t_material_category");
        List includes = Arrays.asList("t_tender_bid_role_resource");
//        List excludeList = Arrays.asList("t_material_category");
        List tablePrefixList = Arrays.asList("base_", "t_", "gl_");
        generate(url, name, password, parentPackage, javaFileOutputDir, xmlFileOutputDir,moduleName,includes,tablePrefixList);
        generateRepository(url, name, password, parentPackage, javaFileOutputDir, xmlFileOutputDir,moduleName,includes,tablePrefixList);
}
    private static void generate(String url, String name, String password, String parentPackage, String javaFileOutputDir,
                                 String xmlFileOutputDir,String moduleName,List includes,List tablePrefixList){
        FastAutoGenerator.create(url, name, password)
                .globalConfig(builder -> builder.author("guoyu")
                        .enableSpringdoc()
                        .outputDir(javaFileOutputDir)
                        .disableOpenDir())
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                }))
                .packageConfig(builder -> builder.parent(parentPackage)
                        .moduleName(moduleName)
                        .entity("domain")
                        .service("service")
                        .serviceImpl("service" + ".impl")
                        .mapper("mapper")
                        .xml("mapper.xml")
                        .controller("controller")
                        .pathInfo(Collections.singletonMap(OutputFile.xml, xmlFileOutputDir)))
                .strategyConfig(builder -> builder
                        .enableCapitalMode()
                        .enableSkipView()
                        .addInclude(includes)
                        .addTablePrefix(tablePrefixList)
//                        .addExclude(excludeList)
                        .entityBuilder()
                        .enableChainModel()
                        .enableFileOverride()
                        .disableSerialVersionUID()
                        .enableLombok()
                        .versionColumnName("version")
                        .versionPropertyName("version")
//                        .logicDeleteColumnName("deleted")
//                        .logicDeletePropertyName("deleted")
                        .naming(NamingStrategy.underline_to_camel)
                        .columnNaming(NamingStrategy.underline_to_camel)
                        .addTableFills(new Column("create_time", FieldFill.INSERT)
//                                new Column("update_time", FieldFill.INSERT)
                        )
                        .controllerBuilder()
                        .enableFileOverride()
                        .formatFileName("%sController")
                        .enableRestStyle()

                        .serviceBuilder()
                        .enableFileOverride()
//                        .superServiceClass(SuperService.class)
//                        .superServiceImplClass(SuperServiceImpl.class)
                        .formatServiceFileName("%sService")
                        .formatServiceImplFileName("%sServiceImpl")

                        .mapperBuilder()
                        .enableFileOverride()
                        .superClass(HussarMapper.class)
                        .enableBaseResultMap()
                        .enableBaseColumnList()
                        .formatMapperFileName("%sMapper"))
                .templateConfig(builder -> builder
                        .entity("/templates/domain.java")
                        .service("/templates/service.java")
                        .serviceImpl("/templates/serviceImpl.java")
                        .mapper("/templates/mapper.java")
//                        .mapper("/templates/repository.java")
                        .xml("/templates/mapper.xml")
                        .controller("/templates/controller.java"))
                .templateEngine(new FreemarkerTemplateEngine())
                .injectionConfig((builder) -> builder.beforeOutputFile((tableInfo, objectMap) -> log.debug("tableInfo - {},objectMap - {}", tableInfo.getEntityName(), objectMap)))
                .execute();
    }


    private static void generateRepository(String url, String name, String password, String parentPackage, String javaFileOutputDir,
                                 String xmlFileOutputDir,String moduleName,List includes,List tablePrefixList){
        FastAutoGenerator.create(url, name, password)
                .globalConfig(builder -> builder.author("quanlin.shu")
                        .enableSpringdoc()
                        .outputDir(javaFileOutputDir)
                        .disableOpenDir())
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                }))
                .packageConfig(builder -> builder.parent(parentPackage)
                        .moduleName(moduleName)
                        .mapper("repository")
                        .pathInfo(Collections.singletonMap(OutputFile.xml, xmlFileOutputDir)))
                .strategyConfig(builder -> builder
                        .enableCapitalMode()
                        .enableSkipView()
                        .addInclude(includes)
                        .addTablePrefix(tablePrefixList)
//                        .addExclude(excludeList)
                        .entityBuilder()
                        .enableChainModel()
                        .enableFileOverride()
                        .disableSerialVersionUID()
                        .enableLombok()
                        .versionColumnName("version")
                        .versionPropertyName("version")
//                        .logicDeleteColumnName("deleted")
//                        .logicDeletePropertyName("deleted")
                        .naming(NamingStrategy.underline_to_camel)
                        .columnNaming(NamingStrategy.underline_to_camel)
                        .addTableFills(new Column("create_time", FieldFill.INSERT)
//                                new Column("update_time", FieldFill.INSERT)
                        )
                        .mapperBuilder()
                        .enableFileOverride()
                        .superClass(HussarMapper.class)
                        .enableBaseResultMap()
                        .enableBaseColumnList()
                        .formatMapperFileName("%sRepository"))
                .templateConfig(builder -> builder
                        .mapper("/templates/repository.java"))
                .templateEngine(new FreemarkerTemplateEngine())
                .injectionConfig((builder) -> builder.beforeOutputFile((tableInfo, objectMap) -> log.debug("tableInfo - {},objectMap - {}", tableInfo.getEntityName(), objectMap)))
                .execute();
    }


}

主类如上图所示

在resource下面定义生成类的格式

根据表结构生成controller,service,repository,domain的工具类_第1张图片

cotroller

package ${package.Entity};

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

<#if entityLombokModel>
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.EqualsAndHashCode;
    <#if chainModel>
import lombok.experimental.Accessors;
    


/**
* @author ${author}
* ${table.comment!}
*/
<#if entityLombokModel>
@Getter
@Setter
    <#if superEntityClass??>
@ToString(callSuper = true)
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
    
<#else>
    <#if chainModel>
        @Accessors(chain = true)
    

<#if table.convert>
@TableName(value = "${schemaName}${table.name}")

<#if superEntityClass??>
<#--public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> {-->
public class ${entity} {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#elseif entitySerialVersionUID>
public class ${entity} implements Serializable {
<#else>
public class ${entity} {

<#if entitySerialVersionUID>

    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>
    <#--        <#if springdoc>-->
    <#--    @Schema(description = "${field.comment}")-->
    <#--        <#else>-->
    /**
    * ${field.comment}
    */
    <#--        -->
    
    <#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}")-->
<#--        -->
    <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
        <#if field.convert>
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
        <#else>
    @TableField(fill = FieldFill.${field.fill})
        
    <#elseif field.convert>
    @TableField("${field.annotationColumnName}")
    
<#-- 乐观锁注解 -->
    <#if field.versionField>
        @Version
    
<#-- 逻辑删除注解 -->
    <#if field.logicDeleteField>
        @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 chainModel>
            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 chainModel>
            return this;
        
        }
    

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

        public static final String ${field.name?upper_case} = "${field.name}";
    

<#if activeRecord>

    @Override
    public 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} +
        
    
    "}";
    }

}

domain

package ${package.Entity};

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

<#if entityLombokModel>
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.EqualsAndHashCode;
    <#if chainModel>
import lombok.experimental.Accessors;
    


/**
* @author ${author}
* ${table.comment!}
*/
<#if entityLombokModel>
@Getter
@Setter
    <#if superEntityClass??>
@ToString(callSuper = true)
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
    
<#else>
    <#if chainModel>
        @Accessors(chain = true)
    

<#if table.convert>
@TableName(value = "${schemaName}${table.name}")

<#if superEntityClass??>
<#--public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> {-->
public class ${entity} {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#elseif entitySerialVersionUID>
public class ${entity} implements Serializable {
<#else>
public class ${entity} {

<#if entitySerialVersionUID>

    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>
    <#--        <#if springdoc>-->
    <#--    @Schema(description = "${field.comment}")-->
    <#--        <#else>-->
    /**
    * ${field.comment}
    */
    <#--        -->
    
    <#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}")-->
<#--        -->
    <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
        <#if field.convert>
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
        <#else>
    @TableField(fill = FieldFill.${field.fill})
        
    <#elseif field.convert>
    @TableField("${field.annotationColumnName}")
    
<#-- 乐观锁注解 -->
    <#if field.versionField>
        @Version
    
<#-- 逻辑删除注解 -->
    <#if field.logicDeleteField>
        @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 chainModel>
            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 chainModel>
            return this;
        
        }
    

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

        public static final String ${field.name?upper_case} = "${field.name}";
    

<#if activeRecord>

    @Override
    public 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 

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
<#if mapperAnnotationClass??>
    import ${mapperAnnotationClass.name};

import org.apache.ibatis.annotations.Mapper;

/**
* @author ${author}
*/
<#if mapperAnnotationClass??>
    @${mapperAnnotationClass.simpleName}

<#if kotlin>
@Mapper
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
@Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}

mapper.xml 





    <#if enableCache>
        
        

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

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

    

 

Repository
package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;

/**
* @author ${author}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>()<#if table.serviceInterface>, ${table.serviceName} {

}
<#else>
@Repository
<#--public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}><#if table.serviceInterface> implements ${table.serviceName} {-->
public class ${entity}Repository {

    @Resource
    private ${entity}Mapper ${table.entityPath}Mapper;

    public void insert(${entity} ${table.entityPath}){
        ${table.entityPath}Mapper.insert(${table.entityPath});
    }

    public void updateById(${entity} ${table.entityPath}){
        ${table.entityPath}Mapper.updateById(${table.entityPath});
    }

    public ${entity} getById(Long id, Long tenantId){
        LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(${entity}::getTenantId, tenantId).eq(${entity}::getId, id);
        return ${table.entityPath}Mapper.selectOne(queryWrapper);
    }

    public void deleteBatchIds(List ids, Long tenantId){
        LambdaUpdateWrapper<${entity}> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(${entity}::getTenantId,tenantId).in(${entity}::getId,ids)
        .set(${entity}::getDeleteFlag, DeleteStatusEnum.DELETED);
        ${table.entityPath}Mapper.update(null,updateWrapper);
    }

}

service 

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import javax.annotation.Resource;
import java.util.List;

/**
* @author ${author}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
<#--public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {-->

<#--}-->
public interface ${table.serviceName} {

    void save(${entity} ${table.entityPath});

    void update(${entity} ${table.entityPath});

    ${entity} getById(Long id, Long tenantId);

    void delete(List ids, Long tenantId);
}

serviceImpl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${entity}Repository;
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author ${author}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>()<#if table.serviceInterface>, ${table.serviceName} {

}
<#else>
<#--public class ${table.serviceImplName} extends ${HussarServiceImplClass}<${table.mapperName}, ${entity}><#if table.serviceInterface> implements ${table.serviceName} {-->
public class ${table.serviceImplName} implements ${table.serviceName} {

    @Resource
    private ${entity}Repository ${table.entityPath}Repository;

    @Override
    public void save(${entity} ${table.entityPath}){
        ${table.entityPath}Repository.insert(${table.entityPath});
    }

    @Override
    public void update(${entity} ${table.entityPath}){
        ${table.entityPath}Repository.updateById(${table.entityPath});
    }

    @Override
    public ${entity} getById(Long id, Long tenantId){
        return ${table.entityPath}Repository.getById(id, tenantId);
    }

    @Override
    public void delete(List ids, Long tenantId){
        ${table.entityPath}Repository.deleteBatchIds(ids, tenantId);
    }

}

 

你可能感兴趣的:(java)