码迷,mamicode.com
首页 > 其他好文 > 详细

代码自动生成

时间:2020-03-26 19:05:03      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:配置   upd   XML   convert   table   file   get   自动   creat   

<!--  generator -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.0.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.2</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>1.7.30</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!--  generator -->

 

项目添加VM文件   src\main\resources\template\mapper.xml.vm,   src\main\resources\template\domain.java.vm

 

domain.java.vm

package ${package.Entity};

#if(${activeRecord})
import java.io.Serializable;

#end
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${entityLombokModel})
import com.baomidou.mybatisplus.annotations.Version;
import lombok.Data;
#end

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
#end
@Api(tags = "${entity}", description = "${table.comment}")
#if(${table.convert})
@TableName("${table.name}")
#end

public class ${entity} implements Serializable {

    private static final long serialVersionUID = 1L;

##
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end

#if("$!field.comment" != "")
@ApiModelProperty(value = "${field.comment}",name="${field.propertyName}")
#end
#if(${field.keyFlag})
##
#if(${field.keyIdentityFlag})
    @TableId(value="${field.name}", type= IdType.AUTO)
#elseif(${field.convert})
    @TableId("${field.name}")
#end
##
#elseif(${field.fill})
## 
#if(${field.convert})
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
    @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
#if(${field.name}=="create_by_id" || ${field.name}=="create_by_name" || ${field.name}=="create_time"
                     || ${field.name}=="update_by_id" || ${field.name}=="update_by_name" || ${field.name}=="update_time")
    @TableField(value = "${field.name}", fill = FieldFill.INSERT)
#else
    @TableField("${field.name}")
#end
#end
## 
#if(${versionFieldName}==${field.name})
    @Version
#end
##
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
    private ${field.propertyType} ${field.propertyName};
#end
## 

#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

    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}) {
#end
        this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
        return this;
#end
    }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end

#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{velocityCount}==1)
            "${field.propertyName}=" + ${field.propertyName} +
#else
            ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
            "}";
    }
#end
}

 

mapper.xml.vm

<?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(${enableCache})
        <!-- 开启二级缓存 -->
        <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

    #end
    #if(${baseResultMap})
        <!-- 通用查询映射结果 -->
        <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
            #foreach($field in ${table.fields})
                #if(${field.keyFlag})##生成主键排在第一位
                    <id column="${field.name}" property="${field.propertyName}" />
                #end
            #end
            #foreach($field in ${table.commonFields})##生成公共字段
                <result column="${field.name}" property="${field.propertyName}" />
            #end
            #foreach($field in ${table.fields})
                #if(!${field.keyFlag})##生成普通字段
                    <result column="${field.name}" property="${field.propertyName}" />
                #end
            #end
        </resultMap>

    #end
    #if(${baseColumnList})
        <!-- 通用查询结果列 -->
        <sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
            ${field.name},
#end
        ${table.fieldNames}
    </sql>

    #end
</mapper>

 

package generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.config.rules.PropertyInfo;

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

/**
 * <p>
 * 代码生成器演示
 * </p>
 */
public class CodeGenerator {
    
    /**
     * 修改生成配置
     * */
    public static String dbUrl = "jdbc:mysql://127.0.0.1:3306/数据库名?useUnicode=true&useSSL=false&characterEncoding=utf8";
    
    public static String dbName = "root";
    
    public static String dbPassword = "root";
    
    public static String[] removePreTableName = new String[] {""};
    
    //生成路径
    public static String parentpackage = "cn.com.xxx";
    
    //需要执行生成策略的表
    public static String[] tables = new String[] { 
            "TB_USER_INFO"
            };
    
    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor("XXX");

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public PropertyInfo processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                return super.processTypeConvert(globalConfig, fieldType);
            }
            
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(dbName);
        dsc.setPassword(dbPassword);
        dsc.setUrl(dbUrl);
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(removePreTableName);// 此处可以修改移除表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tables); // 需要生成的表
        strategy.setEntityLombokModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(parentpackage);
        pc.setModuleName("");
        pc.setEntity("domain");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/template/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath+"/src/main/resources/mybatis/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        tc.setEntity("/template/domain.java.vm");
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

    }

}

 

代码自动生成

标签:配置   upd   XML   convert   table   file   get   自动   creat   

原文地址:https://www.cnblogs.com/bevis-byf/p/12576246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!