栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis-Plus 自动生成代码-当前最新版

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis-Plus 自动生成代码-当前最新版

Mybatis-Plus generator 3.5.1 自动生成代码
    • @[TOC](Mybatis-Plus generator 3.5.1 自动生成代码)
        • 起源
        • 说明、问题、解决
        • 代码
        • 模板案例
        • XML模板案例
起源

升级了下mybatis-plus版本,随之把自动生成代码插件也升级了,改动随之贴个代码。
pom信息:

 	
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus-boot-starter.version}
        
        
            com.baomidou
            mybatis-plus-extension
            ${mybatis-plus-boot-starter.version}
        
        
            com.baomidou
            mybatis-plus-generator
            ${mybatis-plus-generator.version}
        
        
            org.apache.velocity
            velocity-engine-core
            ${velocity-engine-core.version}
        

版本信息:

	3.4.3.4
    3.5.1
    2.3
说明、问题、解决
1. 使用的是velocity做模板引擎,为了兼容之前的,自定义变量、自定义模板
2. 基本使用的是自定义模板,模板大家需求都不太一样,所以这里不贴太多,只发一两个做参考
3. 重写了templateEngine的outputCustomFile方法,主要是因为希望自己定义自定义模板的生成路径
代码
package com.momomian.admin.generator.code;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CurdGenerator {
    private static String author = "momomian";
    private static String url = "jdbc:mysql://localhost:3306/mmm-life?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    private static String username = "root";
    private static String password = "123456";
    //输出目录
    private static String outputDir = System.getProperty("user.dir") + "/admin/src/main/java";
    //父包
    private static String parentPackage = "com.momomian.admin";
    //模块名
    private static String moduleName = "sys";
    //表名
    private static String tableName = "t_user";
    private static String tablePrefix = "t_";
    // 表有无创建时间日期字段
    private static boolean existDate = false;

    private static String createDateName = "createDate";
    private static String updateDateName = "updateDate";
    // 全局响应类名
    private static String allResultApiName = "ApiResult";

    
    private static final DataSourceConfig.Builder DATA_SOURCE_ConFIG = new DataSourceConfig
            .Builder(url, username, password)
            //数据库查询
            .dbQuery(new MySqlQuery())
            //数据库类型转换器
            .typeConvert(new MySqlTypeConvert())
            //数据库关键字处理器
            .keyWordsHandler(new MySqlKeyWordsHandler());
    
    private static FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(DATA_SOURCE_CONFIG);


    public static void main(String[] args) {
        genCode();
    }

    
    public static void globalConfig() {
        fastAutoGenerator.globalConfig(builder -> {
            // 设置作者
            builder.author(author)
                    // 开启 swagger 模式
                    //.enableSwagger()
                    // 覆盖已生成文件
                    .fileOverride()
                    //禁止生成代码后自动弹出输出目录
                    .disableOpenDir()
                    // 时间策略
                    .dateType(DateType.TIME_PACK)
                    //注释日期,默认值: yyyy-MM-dd
                    .commentDate("yyyy-MM-dd")
                    // 指定输出目录
                    .outputDir(outputDir);
        });
    }

    
    public static void packageConfig() {
        fastAutoGenerator.packageConfig(builder -> {
            // 设置父包名
            builder.parent(parentPackage)
                    // 设置父包模块名
                    .moduleName(moduleName)
                    .entity("po")
                    .service("service")
                    .serviceImpl("service.impl")
                    .mapper("mapper")
                    .xml("mapper.xml")
                    .controller("controller")
                    //设置自定义的文件包名,默认是other,这边取消掉
                    .other("")
                    // 设置mapperXml生成路径
                    .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "admin/src/main/resources/mapper"));
        });
    }

    
    public static void templateConfig() {
        fastAutoGenerator.templateConfig((scanner, builder) -> builder
                .entity("/template/entity.java")
                .service("/template/service.java")
                .serviceImpl("/template/serviceImpl.java")
                .mapper("/template/mapper.java")
                .mapperXml("/template/mapper.xml")
                .controller("/template/controller.java")
        );
    }

    
    public static void injectionConfig() {
        Map fileMap = new HashMap<>();

        Map fieldMap = new HashMap<>();

        fastAutoGenerator.injectionConfig(builder -> builder
                //输出文件之前消费者
                .beforeOutputFile((tableInfo, objectMap) -> {
                    String entityName = tableInfo.getEntityName();
                    Map aPackageMap = (Map) objectMap.get("package");
                    //自定义字段,模板变量  直接粗暴加objectMap,因为加入fieldMap会不生效(源码里写的是先把customMap.putAll到objectMap,再执行的这里--哭了)
                    objectMap.put("table_name", entityName.substring(0, 1).toLowerCase() + entityName.substring(1));
                    objectMap.put("model", aPackageMap.get("Parent") + ".model");
                    objectMap.put("bean", entityName.replace("PO", ""));
                    objectMap.put("vo", entityName + "VO");
                    objectMap.put("convert", entityName + "Convert");
                    objectMap.put("dto", entityName + "DTO");
                    objectMap.put("query", entityName + "Query");
                    objectMap.put("common", "com.momomian.common");
                    diyConfig(objectMap);

                    //自定义生成文件配置
                    fileMap.put("\model\vo\" + entityName + "VO.java", "/template/vo.java.vm");
                    fileMap.put("\model\convert\" + entityName + "Convert.java", "/template/convert.java.vm");
                    fileMap.put("\model\dto\" + entityName + "DTO.java", "/template/dto.java.vm");
                    fileMap.put("\model\query\" + entityName + "Query.java", "/template/query.java.vm");
                })
                // 自定义属性,模板变量
                .customMap(fieldMap)
                .customFile(fileMap)

        );

    }

    
    private static void diyConfig(Map objectMap) {
        //设定entityLombokModel为true,使用lombok
        objectMap.put("entityLombokModel", true);
        //表有无创建时间日期字段
        objectMap.put("existDate", existDate);
        //时间字段set方法定义
        objectMap.put("setCreateDate", "set" + createDateName.substring(0, 1).toUpperCase() + createDateName.substring(1));
        objectMap.put("setUpdateDate", "set" + updateDateName.substring(0, 1).toUpperCase() + updateDateName.substring(1));
        objectMap.put("ApiResult", allResultApiName);
        objectMap.put("baseResultMap", true);
        objectMap.put("baseColumnList", true);
    }


    
    public static void strategyConfig() {

        fastAutoGenerator.strategyConfig(builder -> {
            // 设置需要生成的表名
            builder.addInclude(tableName)

                    // 设置过滤表前缀
                    .addTablePrefix(tablePrefix);
        });
    }

    
    public static void templateEngine() {
        fastAutoGenerator.templateEngine(new VelocityTemplateEngine() {

            
            @Override
            protected void outputCustomFile(Map customFile, TableInfo tableInfo, Map objectMap) {
                String otherPath = getPathInfo(OutputFile.other);
                customFile.forEach((key, value) -> {
                    String fileName = String.format((otherPath + File.separator + "%s"), key);
                    outputFile(new File(fileName), objectMap, value);
                });
            }
        });

    }

    public static void genCode() {
        globalConfig();
        packageConfig();
        templateConfig();
        strategyConfig();
        injectionConfig();
        templateEngine();
        fastAutoGenerator.execute();
    }
}
模板案例
package $!{model}.vo;
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end


import lombok.Data;
import lombok.NoArgsConstructor;
#foreach($pkg in ${table.importPackages})
import $!{pkg};
#end


@Data
@NoArgsConstructor
#if(${swagger2})
@ApiModel(value="$!{vo}视图对象")
#end
public class $!{vo} implements Serializable {

    private static final long serialVersionUID = 1L;


## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})

    #if(${field.keyFlag})
        #set($keyPropertyName=${field.propertyName})
    #end
    #if("$!field.comment" != "")
        #if(${swagger2})
    @ApiModelProperty(value = "$!{field.comment}")
        #else
    
        #end
    #end
    private $!{field.propertyType} $!{field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

}
XML模板案例

mapper.xml.vm





    #if(${enableCache})
        
        
    #end
    #if(${baseResultMap})
        
    
            #foreach($field in ${table.fields})
                #if(${field.keyFlag})##生成主键排在第一位
        
                #end
            #end
            #foreach($field in ${table.commonFields})##生成公共字段
        
            #end
            #foreach($field in ${table.fields})
                #if(!${field.keyFlag})##生成普通字段
        
                #end
            #end
    
    #end

    #if(${baseColumnList})
    
    
#foreach($field in ${table.commonFields})
        ${field.name},
#end
        ${table.fieldNames}
    
    #end

    
    ${table.name}
    
    #set($i=${table.name.lastIndexOf('_')})
    #set($alias=${table.name.substring($i+1)})
    ${table.name} as ${alias}


    
        select count(1)
        from ${table.name}
        
            #foreach($field in ${table.fields})
                
                    and ${field.name} = #{query.${field.propertyName}}
                
            #end
        

    

    
        INSERT INTO ${table.name}(
        
            #foreach($field in ${table.fields})
                
                    ${field.name} ,
                
            #end
        
        )VALUES(
        
            #foreach($field in ${table.fields})
                
                    #{po.${field.propertyName}},
                
            #end
        
        )
    

    
        select 
        from ${table.name}
        
            #foreach($field in ${table.fields})
                
                    and ${field.name} = #{query.${field.propertyName}}
                
            #end
        
    


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号