mybatis-plus-generator 模板生成代码
maven:
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
java(CodeGenerator):
package com.youlan; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator { /**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
} public static void main(String[] args) { // 代码生成器
AutoGenerator mpg = new AutoGenerator();
mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("terry.qian");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
gc.setEntityName("%sModel"); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.1.104:3306/freport?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.baomidou.ant");
mpg.setPackageInfo(pc); // 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
}; // 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg); // 配置模板
TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController(); templateConfig.setEntity("templates/custommodel");
mpg.setTemplate(templateConfig); // 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.deloitte.freport.dbase.IEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true); // 公共父类
strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
} }
freemarker(custommodel.ftl):
package ${package.Entity}; import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.util.Date;
import com.deloitte.freport.annotation.QuotaCodeAnn
import com.deloitte.freport.enums.QuotaEnum;
<#assign xxx = ["mi_business_type_l3","mi_business_type_l2","sub_channel_l2","distribution_channel_l3","distribution_channel_l2","insurance_type_l3","insurance_type_l2","type","product_type","business_type_l3","business_type_l2","business_type_l4","higher_product_level","medical_insurance_type","business_type_l3","create_time","last_changed","settled_time","status", "org_type", "org","business_type_merge","insurance_type_l4","business_type_merge"]/> <#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel> import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if> /**
* <p>
* <#if table.comment??>${table.comment}</#if>
* </p>
*
* @table ${table.name}
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
</#if>
<#if superEntityClass??>
public class ${entity} implements ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if> private static final long serialVersionUID = 1L;
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if> <#if field.comment!?length gt 0>
/**
* ${field.comment}
*/
</#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??>
<#-- ----- 存在字段填充设置 ----->
<#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>
<#if xxx?seq_contains(field.name)>
@Column(column = "${field.name}")
private ${field.propertyType} ${field.propertyName};
<#else>
@Column(column = "${field.name}")
@QuotaCodeAnn(codeEnum = QuotaEnum.${field.name})
private ${field.propertyType} ${field.propertyName};
</#if>
</#list>
<#------------ END 字段循环遍历 ----------> <#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 this.id;
</#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>
}
mybatis-plus-generator 模板生成代码的更多相关文章
- 修改mybatis plus Generator模板生成字段注释枚举常量
修改mybatis plus Generator模板生成字段注释枚举常量 本文基于最新的mybatis-plus 3.0.1版本源码修改,如果使用其它版本,处理方式也类似,主要是生成Entity的Fr ...
- MyBatis使用Generator自动生成代码
MyBatis中,可以使用Generator自动生成代码,包括DAO层. MODEL层 .MAPPING SQL映射文件. 第一步: 配置好自动生成代码所需的XML配置文件,例如(generator. ...
- 【Mybatis】MyBatis之Generator自动生成代码(九)
MyBatis Generator 简介 MyBatis Generator 连接数据库表并生成MyBatis或iBatis文件.这有助于最大限度地减少使用MyBatis时为数据库文件创建简单CRUD ...
- Mybatis的generator自动生成代码
mybatis-generator有三种用法:命令行.ide插件.maven插件.本次使用maven生成 环境:IDEA,mysql8,maven (1):新建项目,本次以SpringBoot项目为例 ...
- SpringBoot 添加mybatis generator 自动生成代码插件
自动生成数据层代码,提高开发效率 1.pom添加插件,并指定配置文件路径 <!-- mybatis generator 自动生成代码插件 --> <plugin> <gr ...
- springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)
这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...
- idea中mybatis generator自动生成代码配置 数据库是sqlserver
好长时间没有写博客了,最近公司要用java语言,开始学习java,属于初学者,今天主要记录一下mybatis generator自动生成代码,首先在如下图的目录中新建两个文件,如下图 generato ...
- SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件
原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...
- IDEA Maven Mybatis generator 自动生成代码
IDEA Maven Mybatis generator 自动生成代码 一.安装配置maven以及在Idea中配置maven 安装过程步骤可以看上面的博文,里面介绍得很详细. 二.建数据表 DROP ...
- Mybatis generator 逆向生成代码
Mybatis generator 逆向生成代码 简单介绍 本文介绍用mybatis逆向生成javaben dao接口 1.创建maven项目 创建相应的包 附上项目创建完成的图片 然后在pom.xm ...
随机推荐
- Android Okhttp POST提交键值对
以前的项目网络连接那块一直坚持使用HttpClient,总是会出现一些莫名奇妙的问题,现在新的项目使用了OKHttp网络框架,发现超级好用,上网再了解下,发现OkHttp口碑真的不错,对比之下Http ...
- (原)在anaconda3+ubuntu16.04中编译Pose flow中的deepmatching动态库
转载请注明出处: https://www.cnblogs.com/darkknightzh/p/11285239.html 参考网址: https://github.com/YuliangXiu/Po ...
- nginx 的 重定向
1. ngx.redirect(uri, status?) 301/302重定向 redirect 为外部重定向,有两种形式: rewrite ^ /foo? redirect; # ngi ...
- AjAX 异步通信
<!DOCTYPE html> <html lang="en"> <head> <title>xmlhttprequest ajax ...
- luoguP5495:Dirichlet 前缀和
题意:给定数组a[]的生成方式,然后b[i]=∑a[j] ,(i%j==0),求所有b[i]的异或和.所有运算%2^32; 思路:高维前缀和的思想,先筛出所有素数,然后把每个素数当成一维,那么分开考 ...
- input 关键字提示,对于一些特定优化来说,很有用处
只用html就可以做出提醒操作:效果如下图 这里是代码,怎么样,很简单吧 <form action="/server" method="post"> ...
- mysql小结(了解)
Mysql总结 1.数据库的概念 """ 数据库:库(文件夹).表(表结构文件.表数据文件(索引结构)).字段(数据的描述).记录(数据的本体) 分类:效率问题(内存大于 ...
- jenkins中 Slave使用Docker
原因就不说了,网上的自动化测试Docker教程太不靠谱,还是学学官网吧. 目的: 在现在各种虚拟化的大条件下,还在建立N个节点机器或节点机器搞N个并发,是不是太不方便了. 如果一个机器搞N个并发,在自 ...
- JDOJ 1140: 完数
JDOJ 1140: 完数 题目传送门 Description 一个数如果恰好等于它的因子之和,这个数就称为"完数". 例如,6的因子为1.2.3,而6=1+2+3,因此6是&qu ...
- js面向对象的笼统介绍
**js进阶大纲**简单的表面组成:**对象的属性分两类,一类是数据属性,一类是访问器属性**1,数据属性用来保存数据.2,访问器属性不用来保存数据,而是定义了get,set两个函数,读取属性时,自动 ...