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 模板生成代码的更多相关文章

  1. 修改mybatis plus Generator模板生成字段注释枚举常量

    修改mybatis plus Generator模板生成字段注释枚举常量 本文基于最新的mybatis-plus 3.0.1版本源码修改,如果使用其它版本,处理方式也类似,主要是生成Entity的Fr ...

  2. MyBatis使用Generator自动生成代码

    MyBatis中,可以使用Generator自动生成代码,包括DAO层. MODEL层 .MAPPING SQL映射文件. 第一步: 配置好自动生成代码所需的XML配置文件,例如(generator. ...

  3. 【Mybatis】MyBatis之Generator自动生成代码(九)

    MyBatis Generator 简介 MyBatis Generator 连接数据库表并生成MyBatis或iBatis文件.这有助于最大限度地减少使用MyBatis时为数据库文件创建简单CRUD ...

  4. Mybatis的generator自动生成代码

    mybatis-generator有三种用法:命令行.ide插件.maven插件.本次使用maven生成 环境:IDEA,mysql8,maven (1):新建项目,本次以SpringBoot项目为例 ...

  5. SpringBoot 添加mybatis generator 自动生成代码插件

    自动生成数据层代码,提高开发效率 1.pom添加插件,并指定配置文件路径 <!-- mybatis generator 自动生成代码插件 --> <plugin> <gr ...

  6. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

  7. idea中mybatis generator自动生成代码配置 数据库是sqlserver

    好长时间没有写博客了,最近公司要用java语言,开始学习java,属于初学者,今天主要记录一下mybatis generator自动生成代码,首先在如下图的目录中新建两个文件,如下图 generato ...

  8. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  9. IDEA Maven Mybatis generator 自动生成代码

    IDEA Maven Mybatis generator 自动生成代码 一.安装配置maven以及在Idea中配置maven 安装过程步骤可以看上面的博文,里面介绍得很详细. 二.建数据表 DROP ...

  10. Mybatis generator 逆向生成代码

    Mybatis generator 逆向生成代码 简单介绍 本文介绍用mybatis逆向生成javaben dao接口 1.创建maven项目 创建相应的包 附上项目创建完成的图片 然后在pom.xm ...

随机推荐

  1. QML官方文档:Qt Quick Controls 1和2对比

    Qt Quick Controls有1和2两个版本,在程序中会看到好多1和2版本混合使用的情况. 原文:https://doc.qt.io/qt-5/qtquickcontrols2-differen ...

  2. django 开发Broken pipe from ('127.0.0.1', 58078)问题解决

    最近写的一个项目,前端使用了表单submit提交,后端接收POST数据存储.实际上的逻辑并不复杂, django接收到的时候会产生Broken pipe from ('127.0.0.1', 5807 ...

  3. 英语pyrophane火欧珀pyrophane单词

    pyrophane火欧泊产量稀少,以至于大多数采到宝石的矿主不愿意将它进行切割,即便随形的切割技巧比刻面需要更多的经验也要将其加工成随形,因为这种琢型最能保重.但是与黑欧泊为了保证火彩只能切割成蛋面和 ...

  4. datagrid相关

    int rowID = Convert.ToInt32(dataGrid_OpenBoxScan.CurrentRowIndex.ToString());//得到所选行的行号              ...

  5. kubernetes学习Service之headless和statefulSet结合

    一.首先说headless Service和普通Service的区别 headless不分配clusterIP headless service可以通过解析service的DNS,返回所有Pod的地址 ...

  6. HTTP的发展历史和各个版本差别

    HTTP前世今生 1989年,蒂姆·伯纳斯-李发表论文确立了三项关键技术: URI: 统一资源标志符,作为互联网上资源的唯一身份 HTML: 超文本标记语言,描述超文本文档 HTTP: 超文本传输协议 ...

  7. PHP包管理工具composer

    环境:  centos7 一.linux上安装composer 前提:已安装了php 1. 下载composer安装包 php -r "copy('https://install.phpco ...

  8. 05、ip划分+网络配置+虚拟化基础+基本路由

    -- IP   IANA (Internet Assigned Numbers Authority) ,Internet号分配机构.负责对IP地 址分配规划以及对TCP/UDP公共服务的端口定义.国际 ...

  9. django 自定义分页,网址存储缓存,CBV

    1. 通过切片控制分页 自定义分页: from django.shortcuts import render # Create your views here. from app01.models i ...

  10. BeyondCorps

    This repository provides a short description of the BeyondCorp security model and resources for impl ...