Mybatis-plus 代码生成器 AutoGenerator 的简介和(最详细)使用

本章目录

  • 前言
  • 一、添加依赖
  • 二、自定义参数
    • 1、配置 GlobalConfig(全局配置)
    • 2、 配置 DataSourceConfig(数据源配置)
    • 3、 配置PackageConfig(包名配置)
    • 4、 配置InjectionConfig(自定义配置)
    • 5、 配置TemplateConfig(模板配置)
    • 6、配置StrategyConfig(策略配置)
    • 7、生成
  • 三、演示
    • 1、代码
    • 2、pom.xml文件
    • 3、例子演示

前言

        AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

        使用MyBatis-Plus只是我觉得它很方便,但真到了实际项目中,逻辑复杂的项目,就要斟酌一下了。


一、添加依赖

        MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖。以下是AutoGenerator代码生成器和freemarker模板引擎依赖(模板引擎选一种,也可以自定义模板引擎):

<!--mybatis-plus(springboot版)-->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.4.0</version>
</dependency>
<!--mybatis-plus代码生成器-->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-generator</artifactId>
	<version>3.4.0</version>
</dependency>
<!--Velocity(默认)模板引擎-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>
<!--freemarker模板引擎(博主用的)-->
<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.30</version>
</dependency>
<!--beetl模板引擎-->
<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.2.1.RELEASE</version>
</dependency>

自定义模板引擎例子

// AutoGenerator代码生成器
AutoGenerator generator = new AutoGenerator();

// freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());

// beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());

// custom engine 
generator.setTemplateEngine(new CustomTemplateEngine());

generator.setTemplateEngine(自定义模板引擎);

二、自定义参数

        MyBatis-Plus 的代码生成器提供了大量的自定义参数供用户选择,能够满足绝大部分人的使用需求。以下两个链接分别为官方链接和博主自定义的参数链接(我写的注释全些)。

官方代码生成器使用教程链接

我的自定义参数类GitHub链接(有注释)

1、配置 GlobalConfig(全局配置)

// 全局配置
GlobalConfig gc = new GlobalConfig();
//项目根目录
String projectPath = System.getProperty("user.dir");
//用于多个模块下生成到精确的目录下(我设置在桌面)
//String projectPath = "C:/Users/xie/Desktop";
//代码生成目录
gc.setOutputDir(projectPath + "/src/main/java");
//开发人员
gc.setAuthor("先谢郭嘉");
// 是否打开输出目录(默认值:null)
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(true);
//去掉接口上的I
//gc.setServiceName("%Service");
// 配置时间类型策略(date类型),如果不配置会生成LocalDate类型
gc.setDateType(DateType.ONLY_DATE);
// 是否覆盖已有文件(默认值:false)
gc.setFileOverride(true);
//把全局配置添加到代码生成器主类
mpg.setGlobalConfig(gc);

2、 配置 DataSourceConfig(数据源配置)

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
//数据库连接
dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
// 数据库 schema name
//dsc.setSchemaName("public");
// 数据库类型
dsc.setDbType(DbType.MYSQL);
// 驱动名称
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
//用户名
dsc.setUsername("root");
//密码
dsc.setPassword("430423");
//把数据源配置添加到代码生成器主类
mpg.setDataSource(dsc);

3、 配置PackageConfig(包名配置)

// 包配置
PackageConfig pc = new PackageConfig();
// 添加这个后 会以一个实体为一个模块 比如user实体会生成user模块 每个模块下都会生成三层
// pc.setModuleName(scanner("模块名"));
// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
pc.setParent("com.xxgg.blog");
// Service包名
pc.setService("service");
// Entity包名
pc.setEntity("entity");
// ServiceImpl包名
pc.setServiceImpl("service.impl");
// Mapper包名
pc.setMapper("mapper");
// Controller包名
pc.setController("controller");
// Mapper.xml包名
pc.setXml("mapper");
// 把包配置添加到代码生成器主类
mpg.setPackageInfo(pc);

4、 配置InjectionConfig(自定义配置)

// 自定义配置
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("调用默认方法创建的目录,自定义目录用");
        if (fileType == FileType.MAPPER) {
        	// 已经生成 mapper 文件判断存在,不想重新生成返回 false
            return !new File(filePath).exists();
        }
        // 允许生成模板文件
        return true;
   	}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

5、 配置TemplateConfig(模板配置)

// 配置模板
TemplateConfig templateConfig = new TemplateConfig();

// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();

templateConfig.setXml(null);
mpg.setTemplate(templateConfig);

6、配置StrategyConfig(策略配置)

// 策略配置,我喜欢叫数据库表配置
StrategyConfig strategy = new StrategyConfig();
// 数据库表映射到实体的命名策略:下划线转驼峰
strategy.setNaming(NamingStrategy.underline_to_camel);
// 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 实体是否为lombok模型(默认 false)
strategy.setEntityLombokModel(true);
// 生成 @RestController 控制器
strategy.setRestControllerStyle(true);
// 实体类主键名称设置
strategy.setSuperEntityColumns("id");
// 需要包含的表名,允许正则表达式
//这里我做了输入设置
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
// 需要排除的表名,允许正则表达式
//strategy.setExclude("***");
// 是否生成实体时,生成字段注解 默认false;
strategy.setEntityTableFieldAnnotationEnable(true);
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
// 表前缀
strategy.setTablePrefix(pc.getModuleName() + "_");
// 把数据库配置添加到代码生成器主类
mpg.setStrategy(strategy);

7、生成

// 在代码生成器主类上配置模板引擎
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
//生成
mpg.execute();

三、演示

1、代码

/**
 * @description: 代码生成器
 * @author: 先谢郭嘉
 * @create: 2020-09-29 09:04
 **/
public class CodeGenerator {
     
    /**
     * 

* 读取控制台内容 *

*/
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.isNotBlank(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"); //用于多个模块下生成到精确的目录下(我设置在桌面) //String projectPath = "C:/Users/xie/Desktop"; //代码生成目录 gc.setOutputDir(projectPath + "/src/main/java"); //开发人员 gc.setAuthor("先谢郭嘉"); // 是否打开输出目录(默认值:null) gc.setOpen(false); //实体属性 Swagger2 注解 gc.setSwagger2(true); // 是否覆盖已有文件(默认值:false) gc.setFileOverride(true); //把全局配置添加到代码生成器主类 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); //数据库连接 dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8"); // 数据库 schema name //dsc.setSchemaName("public"); // 数据库类型 dsc.setDbType(DbType.MYSQL); // 驱动名称 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //用户名 dsc.setUsername("root"); //密码 dsc.setPassword("430423"); //把数据源配置添加到代码生成器主类 mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // 添加这个后 会以一个实体为一个模块 比如user实体会生成user模块 每个模块下都会生成三层 // pc.setModuleName(scanner("模块名")); // 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名 pc.setParent("com.xxgg.blog"); // Service包名 pc.setService("service"); // Entity包名 pc.setEntity("entity"); // ServiceImpl包名 pc.setServiceImpl("service.impl"); // Mapper包名 pc.setMapper("mapper"); // Controller包名 pc.setController("controller"); // Mapper.xml包名 pc.setXml("mapper"); // 把包配置添加到代码生成器主类 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("调用默认方法创建的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允许生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 数据库表配置 StrategyConfig strategy = new StrategyConfig(); // 数据库表映射到实体的命名策略:下划线转驼峰 strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行 strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 实体是否为lombok模型(默认 false) strategy.setEntityLombokModel(true); // 生成 @RestController 控制器 strategy.setRestControllerStyle(true); // 实体类主键名称设置 strategy.setSuperEntityColumns("id"); // 需要包含的表名,允许正则表达式 // 这里做了输入设置 strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); // 需要排除的表名,允许正则表达式 //strategy.setExclude("***"); // 是否生成实体时,生成字段注解 默认false; strategy.setEntityTableFieldAnnotationEnable(true); // 驼峰转连字符 strategy.setControllerMappingHyphenStyle(true); // 表前缀 strategy.setTablePrefix(pc.getModuleName() + "_"); // 把数据库配置添加到代码生成器主类 mpg.setStrategy(strategy); // 在代码生成器主类上配置模板引擎 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //生成 mpg.execute(); } }

2、pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.xxgg</groupId>
	<artifactId>blog</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>blog</name>
	<description>先谢郭嘉的博客——springboot后端</description>

	<properties>
		<java.version>1.8</java.version>
		<mybatis.version>2.1.3</mybatis.version>
		<mybatis-plus.version>3.4.0</mybatis-plus.version>
		<generator.version>3.4.0</generator.version>
		<druid.version>1.1.9</druid.version>
		<mysql.version>8.0.21</mysql.version>
		<lombok.version>1.18.12</lombok.version>
		<knife4j.version>2.0.3</knife4j.version>
		<validation.version>2.0.1.Final</validation.version>
		<jackson.version>2.8.9</jackson.version>
		<freemarker.version>2.3.30</freemarker.version>
	</properties>

	<dependencies>
		<!--代码生成器,MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>${
     generator.version}</version>
		</dependency>
		<!--freemarker模板引擎-->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>${
     freemarker.version}</version>
		</dependency>
		<!--mybatis-plus(springboot版)-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>${
     mybatis-plus.version}</version>
		</dependency>
		<!--mybatis持久层-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>${
     mybatis.version}</version>
		</dependency>
		<!--jackson注解jar包,时间格式化注解@JsonFormat就在里面-->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${
     jackson.version}</version>
		</dependency>
		<!--一些校验的依赖,不然启动会报NoClassDefFoundError: javax/validation/constraints/Min-->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>${
     validation.version}</version>
		</dependency>
		<!--SpringBoot单服务架构使用最新版的knife4j依赖,继承swagger依赖,同时增强UI实现-->
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>knife4j-spring-boot-starter</artifactId>
			<version>${
     knife4j.version}</version>
		</dependency>
		<!--lombok-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
			<version>${
     lombok.version}</version>
		</dependency>
		<!--springboot整合druid连接池-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>${
     druid.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
			<version>${
     mysql.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

3、例子演示

输入你需要生成的实体类,多个实体类可以用逗号隔开。

Mybatis-plus 代码生成器 AutoGenerator 的简介和(最详细)使用_第1张图片
生产前的包结构-------------------------------------------------------------------------

Mybatis-plus 代码生成器 AutoGenerator 的简介和(最详细)使用_第2张图片

生成后的包结构-------------------------------------------------------------------------

Mybatis-plus 代码生成器 AutoGenerator 的简介和(最详细)使用_第3张图片
生成后的代码-------------------------------------------------------------------------

/**
 * 

* *

* * @author 先谢郭嘉 * @since 2020-09-30 */
@Data @EqualsAndHashCode(callSuper = false) @TableName("blog") @ApiModel(value="Blog对象", description="") public class Blog implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "主键") @TableId(value = "blogId", type = IdType.AUTO) private Long blogId; @ApiModelProperty(value = "标题") @TableField("title") private String title; @ApiModelProperty(value = "内容") @TableField("content") private String content; @ApiModelProperty(value = "首图地址") @TableField("firstPicture") private String firstPicture; @ApiModelProperty(value = "标签,比如原创、转载、翻译等") @TableField("tab") private String tab; @ApiModelProperty(value = "浏览次数") @TableField("views") private Integer views; @ApiModelProperty(value = "评论次数") @TableField("commentCount") private Integer commentCount; @ApiModelProperty(value = "是否开启赞赏") @TableField("appreciation") private Boolean appreciation; @ApiModelProperty(value = "是否开启版权声明") @TableField("shareStatement") private Boolean shareStatement; @ApiModelProperty(value = "是否开启评论") @TableField("commentBled") private Boolean commentBled; @ApiModelProperty(value = "是否发布") @TableField("published") private Boolean published; @ApiModelProperty(value = "是否推荐") @TableField("recommend") private Boolean recommend; @ApiModelProperty(value = "创建时间") @TableField("createTime") private LocalDate createTime; @ApiModelProperty(value = "更新时间") @TableField("updateTime") private LocalDate updateTime; @ApiModelProperty(value = "博客描述") @TableField("description") private String description; @ApiModelProperty(value = "分类id") @TableField("typeId") private Long typeId; @ApiModelProperty(value = "用户id") @TableField("userId") private Long userId; }

你可能感兴趣的:(mybatis,generator,spring,boot,mybatis,java)