目录
- 正文
- 一、概述
- 二、使用AutoGenerator
- 1. 初始化数据库表结构(以User用户表为例)
- 2. 在 pom.xml 文件中添加 AutoGenerator 的依赖。
- 3. 添加模板引擎依赖
- 4. 全局配置
- 5. 自定义模板生成DTO、VO
- User用户类
- 总结
正文
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
今天的主角是MP推出的一款代码生成器,本文主要来介绍一下它强大的代码生成功能。
一、概述
AutoGenerator 是 MyBatis Plus推出的代码生成器,可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,比Mybatis Generator更强大,开发效率更高。
以往我们使用mybatis generator生成代码正常需要配置mybatis-generator-config.xml,代码配置比较繁琐复杂,比如:
<generatorConfiguration> | |
<context id="myContext" targetRuntime="MyBatis" defaultModelType="flat"> | |
<!-- 注释 --> | |
<commentGenerator> | |
<!-- 是否不生成注释 --> | |
<property name="suppressAllComments" value="true"/> | |
</commentGenerator> | |
<!-- jdbc连接 --> | |
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" | |
connectionURL="jdbc:mysql://ip:/codingmoretiny02?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false" | |
userId="codingmoretiny" | |
password=""> | |
<!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true--> | |
<property name="nullCatalogMeansCurrent" value="true"/> | |
</jdbcConnection> | |
<!-- 类型转换 --> | |
<javaTypeResolver> | |
<property name="forceBigDecimals" value="true"/> | |
</javaTypeResolver> | |
<!-- 生成实体类地址 --> | |
<javaModelGenerator targetPackage="com.codingmore.mbg.po" targetProject="src/main/java"> | |
<!-- 是否针对string类型的字段在set方法中进行修剪,默认false --> | |
<property name="trimStrings" value="true"/> | |
</javaModelGenerator> | |
<!-- 生成Mapper.xml文件 --> | |
<sqlMapGenerator targetPackage="com.codingmore.mbg.mapper" targetProject="src/main/resources"> | |
</sqlMapGenerator> | |
<!-- 生成 XxxMapper.java 接口--> | |
<javaClientGenerator targetPackage="com.codingmore.mbg.dao" targetProject="src/main/java" type="XMLMAPPER"> | |
</javaClientGenerator> | |
<table schema="" tableName="user" domainObjectName="User" | |
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" | |
enableUpdateByExample="false" selectByExampleQueryId="false"> | |
</table> | |
</context> | |
</generatorConfiguration> |
二、使用AutoGenerator
1. 初始化数据库表结构(以User用户表为例)
SET NAMES utfmb4; | |
SET FOREIGN_KEY_CHECKS =; | |
-- ---------------------------- | |
-- Table structure for user | |
-- ---------------------------- | |
DROP TABLE IF EXISTS `user`; | |
CREATE TABLE `user` ( | |
`id` bigint() NOT NULL AUTO_INCREMENT, | |
`username` varchar() CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', | |
`mobile` varchar() CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', | |
`create_by` varchar() CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', | |
`create_time` datetime() NULL DEFAULT NULL COMMENT '创建时间', | |
PRIMARY KEY (`id`) USING BTREE, | |
UNIQUE INDEX `username`(`username`) USING BTREE | |
) ENGINE = InnoDB AUTO_INCREMENT = CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户' ROW_FORMAT = Dynamic; | |
SET FOREIGN_KEY_CHECKS =; |
2. 在 pom.xml 文件中添加 AutoGenerator 的依赖。
<dependency> | |
<groupId>com.baomidou</groupId> | |
<artifactId>mybatis-plus-generator</artifactId> | |
<version>.4.1</version> | |
</dependency> |
3. 添加模板引擎依赖
MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,这里使用Freemarker引擎。
<dependency> | |
<groupId>org.freemarker</groupId> | |
<artifactId>freemarker</artifactId> | |
<version>.3.31</version> | |
</dependency> |
4. 全局配置
package com.shardingspherejdbc.mybatisplus.genertor; | |
import com.baomidou.mybatisplus.annotation.FieldFill; | |
import com.baomidou.mybatisplus.annotation.IdType; | |
import com.baomidou.mybatisplus.generator.FastAutoGenerator; | |
import com.baomidou.mybatisplus.generator.config.OutputFile; | |
import com.baomidou.mybatisplus.generator.config.rules.DateType; | |
import com.baomidou.mybatisplus.generator.fill.Column; | |
import com.baomidou.mybatisplus.generator.fill.Property; | |
import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine; | |
import java.util.Collections; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* 代码生成器 | |
* | |
* @author: austin | |
* @since:/2/6 15:28 | |
*/ | |
public class CodeGenerator { | |
public static void main(String[] args) { | |
// 数据源配置 | |
FastAutoGenerator.create("jdbc:mysql://localhost:/sharding-db0?serverTimezone=GMT%2B8", "root", "admin") | |
.globalConfig(builder -> { | |
builder.author("austin") // 设置作者 | |
.enableSwagger() // 开启 swagger 模式 默认值:false | |
.disableOpenDir() // 禁止打开输出目录 默认值:true | |
.commentDate("yyyy-MM-dd") // 注释日期 | |
.dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK | |
.outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录 | |
}) | |
.packageConfig(builder -> { | |
builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模块名 | |
.controller("controller") //Controller 包名 默认值:controller | |
.entity("entity") //Entity 包名 默认值:entity | |
.service("service") //Service 包名 默认值:service | |
.mapper("mapper") //Mapper 包名 默认值:mapper | |
.other("model") | |
//.moduleName("xxx") // 设置父包模块名 默认值:无 | |
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径 | |
//默认存放在mapper的xml下 | |
}) | |
.injectionConfig(consumer -> { | |
Map<String, String> customFile = new HashMap<>(); | |
// DTO、VO | |
customFile.put("DTO.java", "/templates/entityDTO.java.ftl"); | |
customFile.put("VO.java", "/templates/entityVO.java.ftl"); | |
consumer.customFile(customFile); | |
}) | |
.strategyConfig(builder -> { | |
builder.addInclude("user") // 设置需要生成的表名 可边长参数“user”, “user” | |
.addTablePrefix("tb_", "gms_") // 设置过滤表前缀 | |
.serviceBuilder()//service策略配置 | |
.formatServiceFileName("%sService") | |
.formatServiceImplFileName("%sServiceImpl") | |
.entityBuilder()// 实体类策略配置 | |
.idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id | |
.addTableFills(new Column("create_time", FieldFill.INSERT)) // 自动填充配置 | |
.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE)) | |
.enableLombok() //开启lombok | |
.logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段 | |
.enableTableFieldAnnotation()// 属性加上注解说明 | |
.controllerBuilder() //controller 策略配置 | |
.formatFileName("%sController") | |
.enableRestStyle() // 开启RestController注解 | |
.mapperBuilder()// mapper策略配置 | |
.formatMapperFileName("%sMapper") | |
.enableMapperAnnotation()//@mapper注解开启 | |
.formatXmlFileName("%sMapper"); | |
}) | |
// 使用Freemarker引擎模板,默认的是Velocity引擎模板 | |
//.templateEngine(new FreemarkerTemplateEngine()) | |
.templateEngine(new EnhanceFreemarkerTemplateEngine()) | |
.execute(); | |
} | |
} |
5. 自定义模板生成DTO、VO
package com.shardingspherejdbc.mybatisplus.engine; | |
import com.baomidou.mybatisplus.generator.config.OutputFile; | |
import com.baomidou.mybatisplus.generator.config.po.TableInfo; | |
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; | |
import org.springframework.stereotype.Component; | |
import java.io.File; | |
import java.util.Map; | |
/** | |
* 代码生成器支持自定义[DTO\VO等]模版 | |
* | |
* @author: austin | |
* @since:/2/9 13:00 | |
*/ | |
public class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine { | |
protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) { | |
String entityName = tableInfo.getEntityName(); | |
String otherPath = this.getPathInfo(OutputFile.other); | |
customFile.forEach((key, value) -> { | |
String fileName = String.format(otherPath + File.separator + entityName + "%s", key); | |
this.outputFile(new File(fileName), objectMap, value, true); | |
}); | |
} | |
} |
未生成代码前的项目目录如下:
运行CodeGenerator生成代码:
:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...========================== | |
:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show table status WHERE 1=1 AND NAME IN ('user') | |
:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:1,耗时(ms):26 | |
:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `user` | |
:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[user]的主键为自增主键,会导致全局主键的ID类型设置失效! | |
:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:5,耗时(ms):14 | |
:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!========================== |
项目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。
User用户类
package com.shardingspherejdbc.mybatisplus.entity; | |
import com.baomidou.mybatisplus.annotation.FieldFill; | |
import com.baomidou.mybatisplus.annotation.IdType; | |
import com.baomidou.mybatisplus.annotation.TableField; | |
import com.baomidou.mybatisplus.annotation.TableId; | |
import com.baomidou.mybatisplus.annotation.TableName; | |
import io.swagger.annotations.ApiModel; | |
import io.swagger.annotations.ApiModelProperty; | |
import lombok.Getter; | |
import lombok.Setter; | |
import java.io.Serializable; | |
import java.util.Date; | |
/** | |
* <p> | |
* 用户 | |
* </p> | |
* | |
* @author austin | |
* @since-02-09 | |
*/ | |
public class User implements Serializable { | |
private static final long serialVersionUID =L; | |
private Long id; | |
private String username; | |
private String mobile; | |
private String createBy; | |
private Date createTime; | |
} |
想了解MyBatis Plus代码生成配置可以参考官方配置:代码生成器配置新
总结
对比Mybatis的Generator和MyBatis-Plus的AutoGenerator,就可以得出这样一条结论:后者的配置更简单,开发效率也更高,功能也更强大——可快速生成Mapper、Model、Service、Controller、DTO/VO层代码,到这里AutoGenerator生成器的介绍已经完成