Mybatis-Plus 代码生成器基本使用

参考

https://mp.baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

依赖

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<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>
</dependency>

代码生成类

package com.mozq.boot.mpsand02.mp;

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; /**
* @description:
* @author: changzhou.xie@yuantiaokj.com
* @date: 2019/10/30 8:20
*/
// 演示例子,执行 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(); // 全局配置
GlobalConfig gc = new GlobalConfig();
// String projectPath = System.getProperty("user.dir") + "mp-sand-02";
//E:\mozq\demo_project\shiromp-sand-02 String projectPath = System.getProperty("user.dir") + "/mp-sand-02";
//E:\mozq\demo_project\shiromp-sand-02 gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("mozq");//作者
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
// // dsc.setSchemaName("public");
// dsc.setDriverName("com.mysql.jdbc.Driver");
// dsc.setUsername("root");
// dsc.setPassword("密码");
/*=========== 设置自己的数据库路径 ==========*/
dsc.setUrl("jdbc:mysql://114.215.104.72:3306/smart_sand_sit?serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("zichen");
dsc.setPassword("62672000");
mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
// pc.setParent("com.baomidou.ant");
// pc.setModuleName("mpsand02");
/*=========== 设置 Mapper Entity Service ServiceImpl Controller 所在包 ==========*/
pc.setParent("com.mozq.boot");
pc.setEntity(scanner("实体包"));
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(); /*=========== 设置为null表示不生成相应的文件 ==========*/
templateConfig.setService(null);
templateConfig.setServiceImpl(null);
templateConfig.setController(null);
templateConfig.setXml(null);
templateConfig.setMapper(null);
mpg.setTemplate(templateConfig); // 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
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();
} }

命令行运行

请输入实体包:
mpsand02.pojo.user
请输入表名,多个英文逗号分割:
sys_user,sys_role,sys_permission
08:46:35.345 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
08:46:36.245 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [E:\mozq\demo_project\shiro/mp-sand-02/src/main/java\com\mozq\boot\mpsand02\pojo\user]
08:46:36.434 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.ftl; 文件:E:\mozq\demo_project\shiro/mp-sand-02/src/main/java\com\mozq\boot\mpsand02\pojo\user\SysPermission.java
08:46:36.436 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.ftl; 文件:E:\mozq\demo_project\shiro/mp-sand-02/src/main/java\com\mozq\boot\mpsand02\pojo\user\SysRole.java
08:46:36.439 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.ftl; 文件:E:\mozq\demo_project\shiro/mp-sand-02/src/main/java\com\mozq\boot\mpsand02\pojo\user\SysUser.java
08:46:36.439 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!========================== 实际生成文件:
com.mozq.boot.mpsand02.pojo.user.SysUser
com.mozq.boot.mpsand02.pojo.user.SysRole
com.mozq.boot.mpsand02.pojo.user.SysPermission
package com.mozq.boot.mpsand02.pojo.user;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; /**
* <p>
*
* </p>
*
* @author mozq
* @since 2019-10-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUser implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO)
private Integer id; /**
* 砂厂id
*/
private Integer companyId; /**
* 用户名
*/
private String username; /**
* 密码
*/
private String password; /**
* 真实姓名
*/
private String realName; /**
* 电话号码
*/
private String telephone; /**
* 用户状态 0-禁用 1-启用
*/
private Integer status; /**
* 创建时间
*/
private LocalDateTime createTime; /**
* 系统时间
*/
private LocalDateTime updateTime; /**
* 登录时间
*/
private LocalDateTime loginTime; /**
* 微信openId
*/
private String openId;
}

示例2

package com.ytkj.mozq_excel_server.mp;

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; /**
* @description:
* @author: changzhou.xie@yuantiaokj.com
* @date: 2019/10/30 13:40
*/
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(); // 全局配置
GlobalConfig gc = new GlobalConfig();
/*=========== 项目路径+模块路径 ==========*/
String projectPath = System.getProperty("user.dir") + "/mozq_excel_server";
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("mozq");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://114.215.104.72:3306/smart_sand_sit?serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("zichen");
dsc.setPassword("62672000");
mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.ytkj.mozq_excel_server");
pc.setEntity(scanner("实体包"));
pc.setMapper(scanner("Mapper包"));
pc.setService(scanner("Service包"));
pc.setServiceImpl(scanner("ServiceImpl包"));
pc.setController(scanner("Controller包"));
/*=========== xml文件所在包,默认值为mapper.xml,不需要可以在模板引擎中取消 ==========*/
pc.setXml("");
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<>(); /*=========== 自定义xml文件生成位置 ==========*/
String mapperxml = scanner("xml位置"); // 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/static/mybatis" + mapperxml
+ "/" + 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();
/*=========== 不生成xml文件包 ==========*/
templateConfig.setXml(null);//不生成xml包
mpg.setTemplate(templateConfig); // 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
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();
}
}
请输入实体包:
pojo.car
请输入Mapper包:
dao.car
请输入Service包:
service.car
请输入ServiceImpl包:
service.impl.car
请输入Controller包:
controller.car
请输入xml位置:
/mapper/car
请输入表名,多个英文逗号分割:
car,car_record
package com.ytkj.mozq_excel_server.pojo.car;

import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; /**
* <p>
*
* </p>
*
* @author mozq
* @since 2019-10-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class CarRecord implements Serializable { private static final long serialVersionUID = 1L; /**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id; /**
* 车牌号
*/
@TableField("carLicense")
private String carLicense;
}

记忆点

项目下有子模块

//如果项目下有子模块,则要添加子模块的路径,要以斜杠开头。
String projectPath = System.getProperty("user.dir") + "mp-sand-02";
//E:\mozq\demo_project\shiromp-sand-02 String projectPath = System.getProperty("user.dir") + "/mp-sand-02";
//E:\mozq\demo_project\shiro/mp-sand-02

TemplateConfig控制是否生成相应文件

// 配置模板,可以控制生成哪些
TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController(); /*=========== 设置为null表示不生成相应的文件 ==========*/
templateConfig.setService(null);
templateConfig.setServiceImpl(null);
templateConfig.setController(null);
templateConfig.setXml(null);//不生成xml包,和xml配置文件不是一回事。
templateConfig.setMapper(null);
mpg.setTemplate(templateConfig);

控制xml文件生成位置

// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>(); /*=========== 自定义xml文件生成位置 ==========*/
String mapperxml = scanner("xml位置"); // 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/static/mybatis" + mapperxml
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

Mybatis-Plus 代码生成器基本使用的更多相关文章

  1. 0120 springboot集成Mybatis和代码生成器

    在日常开发中,数据持久技术使用的架子使用频率最高的有3个,即spring-jdbc , spring-jpa, spring-mybatis.详情可以看我之前的一篇文章spring操作数据库的3个架子 ...

  2. mybatis自定义代码生成器(Generator)——自动生成model&dao代码

    花了两天的时间研究了下mybatis的generator大体了解了其生成原理以及实现过程.感觉generator做的非常不错,给开发者也留足了空间.看完之后在generator的基础上实现了自定义的生 ...

  3. 想做时间管理大师?你可以试试Mybatis Plus代码生成器

    1. 前言 对于写Crud的老司机来说时间非常宝贵,一些样板代码写不但费时费力,而且枯燥无味.经常有小伙伴问我,胖哥你怎么天天那么有时间去搞新东西,透露一下秘诀呗. 好吧,今天就把Mybatis-pl ...

  4. mybatis(mysql)代码生成器扩展

    前些天在做我的KSF框架的时候需要用到mybatis代码生成器, 但是发现有一些东西需要调整,主要集中在以下几点: 1. 加入batchInsert  2. 加入batchUpdate 3. mysq ...

  5. 手把手教你Spring Boot整合Mybatis Plus 代码生成器

    一.在pom.xml中添加所需依赖 <!-- MyBatis-Plus代码生成器--> <dependency> <groupId>com.baomidou< ...

  6. 寻找写代码感觉(五)之Mybatis官方代码生成器的使用

    一.Mybatis Generator生成器 见名知意,官方给出的代码生成器.好处就是不用自己写实体类.接口.xml文件了,应对简单增删改查是可以的.复杂的还是需要自己手写sql的. 二.Mybati ...

  7. mybatis maven 代码生成器(mysql)

    pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  8. Spring boot + mybatis + mysql代码生成器

    引入依赖: 在pom文件最下边: <build> <plugins> <!--逆向工程--> <plugin> <groupId>org.m ...

  9. Spring boot + mybatis + oracle代码生成器

    在pom文件中加入依赖: <build> <plugins> <!--逆向工程--> <plugin> <groupId>org.mybat ...

  10. mybatis generator代码生成器的使用

    一.有关mybatis generator的使用可以查看如下网址:http://www.mybatis.org/generator/index.html 二.如下是我自己整理的学习步骤: <1& ...

随机推荐

  1. luoguP4331 [BOI2004]Sequence 数字序列

    题意 大力猜结论. 首先将所有\(a_i\)变为\(a_i-i\),之后求不严格递增的\(b_i\),显然答案不变,最后\(b_i\)加上\(i\)即可. 考虑两种特殊情况: 1.\(a[]\)是递增 ...

  2. python-8-字符串索引与切片

    前言 python访问字符串的值,可以使用方括号来截取字符串,但切片对原来的值是不会改变,如下: 一.索引 1.索引下标查找 # 1.索引 a = 'ABCDPOM' s = a[0] s2 = a[ ...

  3. Unity Shader NPR 卡通渲染

    卡通渲染的主要原理包含两个方面: 1.轮廓线的描边效果 2.模型漫反射离散和纯色高光区域的模拟 描边: 描边的实现方法采用将模型的轮廓线顶点向法线(或顶点)的方向扩展一定的像素得到.也可通过边缘检测( ...

  4. python xpath图片爬取

    import requests from urllib.request import urlretrieve from lxml import etree headers = { 'User-Agen ...

  5. 【大数据】SparkSql 连接查询中的谓词下推处理 (一)

    本文首发于 vivo互联网技术 微信公众号 https://mp.weixin.qq.com/s/YPN85WBNcnhk8xKjTPTa2g 作者:李勇 目录: 1.SparkSql 2.连接查询和 ...

  6. java构建树形列表(带children属性)

    一些前端框架提供的树形表格需要手动构建树形列表(带children属性的对象数组),这种结构一般是需要在Java后台构建好. 构建的方式是通过id字段与父id字段做关联,通过递归构建children字 ...

  7. 【转】EF架构~为EF DbContext生成的实体添加注释(T5模板应用)

    嗨,没法说,EF4的TT模版加上注释后,升级到EF5的TT模版后,注释就不通用了,所以,还得再研究一下,然后把操作方法再分享出来,没辙的微软! T4模版可能有些凌乱,这在T5模版里有了不错的改进,但我 ...

  8. Kubernetes service 代理模式

    Kubernetes service 代理模式 底层流量转发与负载均衡实现:• Iptables(默认)• IPVS IPVS 了解代理模式之IPVS工作原理LVS 基于 IPVS内核调度模块实现的负 ...

  9. Java面试- JVM 内存模型讲解

    经常有人会有这么一个疑惑,难道 Java 开发就一定要懂得 JVM 的原理吗?我不懂 JVM ,但我照样可以开发.确实,但如果懂得了 JVM ,可以让你在技术的这条路上走的更远一些. JVM 的重要性 ...

  10. [笔记] C# 如何获取文件的 MIME Type

    MIME Type 为何物: MIME 参考手册 svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types 常规方式 对于有文件后 ...