Preface
In daily development work, we often need to build the persistent objects (PO) corresponding to various data tables, the interface for operating the database (DAO), and the corresponding XML bound to the DAO by ourselves. These are all repetitive operations and do not require much technical content. At this time, we can't help but wonder, is there a tool that can help us automatically generate these files? The answer is: yes!
The following content of this article is mainly suitable for using MyBatis to do the work of the persistence layer framework. If you are not using MyBatis, then this article may not be suitable for your development scenario.
Introduction to MyBatis Generator
As an independent tool based on MyBatis, MyBatis Generator can meet our above requirements. It can help us generate PO, DAO, XML and other files corresponding to the data table through a simple configuration, minus the time we have to manually generate these files, Effectively improve development efficiency. MyBatis Generator runs in various ways, mainly through the following ways:
- Command Line
- Ant
- Maven
- Java
- Eclipse
And I usually configure and use it in Maven, so this article is mainly based on the Maven environment to explain.
Ready to work
Introduce plug-ins
Now that you want to use MyBatis Generator, you must have configured the database and MyBatis dependencies in our project. If you haven't configured it yet, you can configure it in the pom.xml
file. Here we mainly take the MySQL database as an example.
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
</dependencies>
Then we continue to introduce the relevant configuration of MyBatis Generator.
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
</plugin>
</plugins>
</build>
Plugin configuration
After completing the above steps, we just completed the introduction of MyBatis Generator. To make it work, we also need to configure it pom.xml
mainly has the following points.
- path of the configuration file of the code generator
The main configuration here is the path where the MyBatis Generator configuration file is located. Generally we put it in the resources
path, and the name of the configuration file can be customized. Here I take mybatis-generator-config.xml
as an example. At this time, the following configuration needs to be added to the pom.xml
file.
<configuration>
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
</configuration>
- Whether to overwrite the generated file
Due to project requirements, suppose we need to add new fields in our database tables, and we have used MyBatis Generator to generate related files before. At this point, if we want to add the newly added fields to the originally generated file, the first method can be to manually delete the old file and then regenerate it. The second is to configure in MyBatis Generator, so that every newly generated file will directly overwrite the old file. The specific configuration is as follows, true
means coverage, false
means no coverage.
<configuration>
<overwrite>true</overwrite>
</configuration>
But one thing to note, even if we set to overwrite the old files, MyBatis Generator will only overwrite the original PO and DAO files. At this time, the Mapper will not be overwritten, but will be appended to ensure that we add the sql statement ourselves. Will not be overwritten.
- database driver depends on
Although we have configured the related dependencies of the database in the pom.xml
file of the project, it still needs to be configured again in the MyBatis Generator configuration. At this time, there are two ways for us to choose.
The first is to introduce database dependencies again, the specific configuration method is as follows:
<build>
<plugins>
<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.17</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
The second is to use Maven's includeCompileDependencies
attribute. Generally speaking, our project must have introduced related dependencies of the database, so we configure includeCompileDependencies
at this time, the specific configuration method is as follows:
<configuration>
<includeCompileDependencies>true</includeCompileDependencies>
</configuration>
MyBatis Generator configuration
We have introduced MyBatis Generator in the above steps, and also configured pom.xml
, whether to overwrite the file, and the database dependency configuration. Next, let’s take a look at how to configure MyBatis. Generator performs specific configuration and configures various details in our generated code.
- External configuration file
Generally, we need to import external files, which are mainly used to configure the project database to facilitate our subsequent settings. The way to import external configuration files is also very simple. The specific configuration is as follows:
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="generator.properties"/>
</generatorConfiguration>
- context configuration
In addition to the external configuration, context
is undoubtedly the most important configuration in MyBatis Generator. A context
configuration is as follows:
<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">
</context>
The meaning of each attribute is as follows:
- id : unique identification, non-repeatable, can be customized according to our own preferences.
- : Optional, there are two values to choose from, one is
conditional
, which is also the default value, and the other isflat
, which is a commonly used configuration that means that a table in the database generates a PO corresponding to it. - targetRuntime : optional, there are also two values available here, one is
MyBatis3
, the other isMyBatis3Simple
, the main difference between the two is that the DAO and Mapper generated under different configurations will be different, the latter generates The DAO and Mapper will be much less, only containing the most commonly used daily.
context
In addition to the above configuration, there are many sub-elements that need to be configured, and the number and order of the configuration of these sub-elements are specified. If the configuration is not performed in accordance with the given rules, it will cause errors. Common sub-elements The elements and numbers are configured as follows (sort from top to bottom according to the specified order):
Child element | Minimum number | Maximum number |
---|---|---|
property | 0 | N |
plugin | 0 | N |
commentGenerator | 0 | 1 |
jdbcConnection | ||
javaTypeResolver | 0 | 1 |
javaModelGenerator | 1 | N |
sqlMapGenerator | 0 | 1 |
javaClientGenerator | 0 | 1 |
table | 1 | N |
Next, a simple configuration explanation of each sub-element in turn.
context sub-element configuration
- property
If we want to set the encoding type of our generated files, we can configure it here. The specific configuration is as follows:
<property name="javaFileEncoding" value="UTF-8"/>
- plugin
The PO generated by default only contains each attribute declaration and the setter/getter
corresponding to each attribute. If we want to generate the equals
and hashCode
methods corresponding to the PO, it can be achieved by configuring the following plug-ins.
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
To generate the toString
method, you can use the following plug-in:
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
To generate a serialization method for the model, use the following plug-in:
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
- commentGenerator
This configuration is mainly used to configure the generated comments. By default, comments will be generated, and they will be time stamped. If we do not need these configurations, we can clear them through the following configuration:
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<!-- 是否去除自动生成的时间戳 true:是 : false:否 -->
<property name="suppressDate" value="true"/>
<!-- 是否添加数据库表中字段的注释 true:是 : false:否,只有当suppressAllComments 为 false 时才能生效 -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
- jdbcConnection
Since the corresponding file is to be automatically generated, it must be linked to the database, so we need to configure the database. We have talked about importing external configuration files above. In this way, we can define the configuration of the database in an external file, and then import the The file can be configured, and it can be done through the following specific steps:
<jdbcConnection driverClass="${jdbc.driver-class-name}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
<!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
- javaTypeResolver
It is mainly used to configure the type conversion rules in JDBC and Java. If we do not configure it, the default set of conversion rules will be used. If we need to customize, we can only configure bigDecimal
, NUMERIC
and time types, and cannot configure other types , Otherwise it will cause an error, the specific configuration rules are as follows:
<javaTypeResolver>
<property name="forceBigDecimals" value="true"/>
<property name="useJSR310Types" value="false"/>
</javaTypeResolver>
- forceBigDecimals
This attribute defaults to false
, and at this time it will parse the DECIMAL
and NUMERIC
Integer
. If the attribute is true
, the JDBC DECIMAL
and NUMERIC
types will be parsed as java.math.BigDecimal
.
- useJSR310Types
This attribute defaults to false
, it will parse all JDBC time types as java.util.Date
, if the attribute is true
, it will be parsed according to the following rules:
Before conversion | After conversion |
---|---|
DATE | java.time.LocalDate |
TIME | java.time.LocalTime |
TIMESTAMP | java.time.LocalDateTime |
TIME_WITH_TIMEZONE | java.time.OffsetTime |
TIMESTAMP_WITH_TIMEZONE | java.time.OffsetDateTime |
- javaModelGenerator
This is mainly used to configure the package path and project path where the automatically generated PO is located. Here you need to configure it according to your own needs. Here I take my own configuration as an example. For example, the package where my PO is located is com.cunyu1943.mybatisgeneratordemo.entity
, and the project path is src/main/java
.
<javaModelGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.entity" targetProject="src/main/java">
<!-- 是否让 schema 作为包的后缀,默认为 false -->
<property name="enableSubPackages" value="false"/>
<!-- 是否针对 String 类型的字段在 set 方法中进行修剪,默认 false -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
- sqlMapGenerator
Configure Mapper.xml
is stored. For example, if we want to put it src/main/resources/mapper
path 061b84804b962c, the configuration is as follows:
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
</sqlMapGenerator>
- javaClientGenerator
Configure Mapper
interface is stored. Generally, we store it under the mapper
package of the project. For example, my configuration is:
<javaClientGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.mapper" targetProject="src/main/java"
type="XMLMAPPER">
</javaClientGenerator>
- table
Configure the database table of the code to be automatically generated. Here one table corresponds to one table
. If you want to generate multiple tables, you need to configure multiple table
. The following is a specific example:
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" selectByExampleQueryId="false">
<!--是否使用实际列名,默认为false-->
<property name="useActualColumnNames" value="false" />
</table>
Among them, schema
is the database name. Some databases need to be configured, and some databases do not need to be configured. Here you need to fill in according to the database you are using, but it is recommended to fill in it so that different databases can also be applied. tableName
corresponds to the database table name; domainObjectName
corresponds to the generated entity class name. By default, it does not need to be configured. If it is not configured, it will be converted to the class name according to the Pascal nomenclature; and enableXXXByExample
defaults to true
, which will generate a Example
helper by default. However, this configuration is only targetRuntime="MyBatis3"
to take effect, when targetRuntime="MyBatis3Simple"
, the enableXXXByExample
anyway configuration does not work.
Execute build
After the above configuration, we get the overall MyBatis Generator configuration. The complete configuration is as follows. You can modify the configuration according to your needs and use it.
<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis的代码生成器相关配置-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//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,context的子元素必须按照它给出的顺序
property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?,
javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+
-->
<context id="myContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 设置生成文件的编码-->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 这个插件给生成的Java模型对象增加了equals和hashCode方法 -->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<!-- 增加 toString 方法-->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 生成序列化方法-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 注释 -->
<commentGenerator>
<!-- 是否生成注释 true: 否: false: 是 -->
<property name="suppressAllComments" value="true"/>
<!-- 是否去除时间戳 true:是 : false:否 -->
<property name="suppressDate" value="true"/>
<!-- 是否添加数据库表中字段的注释 true:是 : false:否,只有当suppressAllComments 为 false 时才能生效 -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver-class-name}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
<!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!--是否使用bigDecimal,默认false。
false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
<property name="forceBigDecimals" value="true"/>
<!--默认 false
false,将所有 JDBC 的时间类型解析为 java.util.Date
true,将 JDBC 的时间类型按如下规则解析
DATE -> java.time.LocalDate
TIME -> java.time.LocalTime
TIMESTAMP -> java.time.LocalDateTime
TIME_WITH_TIMEZONE -> java.time.OffsetTime
TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime
-->
<property name="useJSR310Types" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.entity" targetProject="src/main/java">
<!-- 是否让 schema 作为包的后缀,默认为false -->
<property name="enableSubPackages" value="false"/>
<!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成Mapper.xml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
</sqlMapGenerator>
<!-- 生成 XxxMapper.java 接口-->
<javaClientGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.mapper" targetProject="src/main/java"
type="XMLMAPPER">
</javaClientGenerator>
<!-- schema为数据库名,oracle需要配置,mysql不需要配置。
tableName为对应的数据库表名
domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名)
enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
-->
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" selectByExampleQueryId="false">
<!--是否使用实际列名,默认为false-->
<property name="useActualColumnNames" value="false"/>
</table>
</context>
</generatorConfiguration>
Among them, the configuration of the external file generator.properties
is specifically as follows, mainly to configure the relevant attributes of the database.
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/community?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.driver-class-name=com.mysql.cj.jdbc.Driver
Finally, when all the configurations are completed, the Maven tool can be used to generate code. The specific operation method is as follows, just click MyBatis Generator in the project Maven configuration.
Summarize
The above is the specific construction process of using Maven with MyBatis Generator to configure and generate project PO, Mapper, XXXMapper.xml. If you happen to have this need, then go and try it. If you encounter any problems during the construction process, please leave a message in the comment area and I will reply as soon as I see it.
Finally, about the relevant code of this example, I have uploaded it to Github, if you have a brother in need, you can pick it up.
🎉🎉🎉 Portal-> mybatis-generator-demo
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。