Spring Boot项目中使用MyBatis Generator (MBG) 自动生成Mapper文件可以很大程度上减少编码。本文着重介绍如何在实战中使用MGB自动生成Mapper文件
1. 添加MyBatis Generator依赖
在pom.xml中添加必要的依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version>
</dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope><version>8.0.28</version>
</dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.7</version>
</dependency><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.4.0</version><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.23</version></dependency></dependencies>
</plugin>
根据自需进行添加相关的依赖jar包。上面是基于MySQL,如果你是SQL Server或者别的数据库还需要自行引入相关依赖。如 SQL Server
<dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId>
</dependency>
2. 创建自动生成代码配置
在resource目录下创建generator.properties 和 generator-config.xml两个配置文件
① generator.properties:配置文件用来 添加数据库连接信息 (可选择性创建)
② generator-config.xml:用于生成代码时 指定生成的 目录路径、代码函数
2.1 generator.properties
jdbc.driver-class=com.mysql.cj.jdbc.Driver
jdbc.connection.url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root123456
2.2 generator-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration>
<properties resource="generator.properties"/>
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"><property name="beginningDelimiter" value="`"/><property name="endingDelimiter" value="`"/><property name="javaFileEncoding" value="UTF-8"/><!-- 为模型生成序列化方法--><plugin type="org.mybatis.generator.plugins.SerializablePlugin"/><!-- 为生成的Java模型创建一个toString方法 --><plugin type="org.mybatis.generator.plugins.ToStringPlugin"/><!--生成mapper.xml时覆盖原文件--><plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/><!--可以自定义生成代码注释--><commentGenerator type="com.demo.example.utils.CommentGenerator"><!-- 是否去除自动生成的注释 true:是 : false:否 --><property name="suppressAllComments" value="true"/><property name="suppressDate" value="true"/><property name="addRemarkComments" value="true"/></commentGenerator><!--配置数据库连接--><jdbcConnection driverClass="${jdbc.driver-class}"connectionURL="${jdbc.connection.url}"userId="${jdbc.username}"password="${jdbc.password}"><!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--><property name="nullCatalogMeansCurrent" value="true"/></jdbcConnection><!--指定生成model的路径--><javaModelGenerator targetPackage="com.demo.example.entity" targetProject="src\main\java"/><!--指定生成mapper.xml的路径--><sqlMapGenerator targetPackage="mappers" targetProject="src\main\resources"/><!--指定生成mapper接口的的路径--><javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.example.mapper"targetProject="src\main\java"/><!--生成全部表tableName设为%--><table tableName="table_name" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"><property name="useActualColumnNames" value="false"/><property name="constructorBased" value="false"/><generatedKey column="id" sqlStatement="JDBC" identity="true"/></table></context>
</generatorConfiguration>
3. 自定义备注添加器CommentGenerator
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;import java.util.Properties;/*** @author*/
public class CommentGenerator extends DefaultCommentGenerator {private boolean addRemarkComments = false;@Overridepublic void addConfigurationProperties(Properties properties) {super.addConfigurationProperties(properties);this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));}@Overridepublic void addFieldComment(Field field, IntrospectedTable introspectedTable,IntrospectedColumn introspectedColumn) {String remarks = introspectedColumn.getRemarks();if (addRemarkComments && StringUtility.stringHasValue(remarks)) {addJavaDoc2Field(field, remarks);}}private void addJavaDoc2Field(Field field, String remarks) {field.addJavaDocLine("/**");String[] remarkLines = remarks.split(System.getProperty("line.separator"));for (String remarkLine : remarkLines) {field.addJavaDocLine(" * " + remarkLine);}addJavadocTag(field, false);field.addJavaDocLine(" */");}}
我的CommentGenerator是创建在utils包下的,随意创建,只需要把第2步的commentGenerator标签中的type属性值替换一下
<commentGenerator type="替换成自己的包路径"></commentGenerator>
4. 创建代码生成器 Generator
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;/*** @author* @description*/
public class Generator {public static void main(String[] args) throws Exception {List<String> warnings = new ArrayList<>();boolean overwrite = true;//读配置文件InputStream is = Generator.class.getResourceAsStream("/generator-config.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(is);is.close();DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);for (String warning : warnings) {System.out.println(warning);}}
}
以上关于Spring Boot项目中使用MBG自动生成Mapper文件相关配置就介绍完了,最后只需要修改成指定的表名,执行Generator类的main方法就可以了
可以看到执行的结果已经在相应的目录下创建了PO实体类、Mapper接口和*Mapper.xml文件
几乎常用的SQL都已经生成了
总结一下:上面代码几乎可以直接粘贴复制使用,需要自己修改的地方有一下几处: