Gangmax Blog

自由之思想,独立之精神

Generate Java Code with MyBatis Generator

This is a note about how to use MyBatis to generate Java code by given database and configuration.

First, create your database tables or update them.

1
2
3
alter table data_fun.bi_sheet add column joined_columns longtext after categories;
alter table data_fun.bi_sheet add column joined_sheets longtext after joined_columns;
alter table data_fun.bi_sheet add column joined_relations longtext after joined_sheets;

Then create or update the “src/main/resources/generatorConfig.xml” configuration file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
<classPathEntry
location="/home/user/mysql-connector-java-5.1.42-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType ="flat" >
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="com.test.exp.util.MybatisLimitPlugin"/>

<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.177.79:3306/data_fun?characterEncoding=UTF8"
userId="user"
password="password">
</jdbcConnection>

<javaModelGenerator targetPackage="com.test.exp.orm.model" targetProject="/home/user/code/xdata/exp/src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>

<sqlMapGenerator targetPackage="com.test.exp.orm.mapper" targetProject="/home/user/code/xdata/exp/src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>

<javaClientGenerator type="XMLMAPPER" targetPackage="com.test.exp.orm.mapper" targetProject="/home/user/code/xdata/exp/src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>

<table schema="sq_slfile" tableName="bi_sheet" domainObjectName="Sheet">
<property name="useActualColumnNames" value="false"/>
<generatedKey column="id" sqlStatement="MYSQL" identity="true"/>
<columnOverride column="sheet_type" javaType="Byte"/>
</table>

</context>
</generatorConfiguration>

The “pom.xml” file should have the following content to use the MyBatis Generator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.4</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>com.exp</groupId>
<artifactId>pagination</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

Note the “pagination” dependency here, you need to install it manually:

1
mvn install:install-file -Dfile=/home/user/pagination-1.0.0.jar  -DgroupId=com.exp  -DartifactId=pagination -Dversion=1.0.0 -Dpackaging=jar

It contains only one class whose code is list below:

MybatisLimitPlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.test.exp.util;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.XmlElement;

public class MybatisLimitPlugin extends org.mybatis.generator.api.PluginAdapter
{
public MybatisLimitPlugin() {}

public boolean validate(java.util.List<String> list)
{
return true;
}

public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable)
{
org.mybatis.generator.api.dom.java.PrimitiveTypeWrapper integerWrapper = FullyQualifiedJavaType.getIntInstance().getPrimitiveTypeWrapper();

Field limit = new Field();
limit.setName("limit");
limit.setVisibility(JavaVisibility.PRIVATE);
limit.setType(integerWrapper);
topLevelClass.addField(limit);

Method setLimit = new Method();
setLimit.setVisibility(JavaVisibility.PUBLIC);
setLimit.setName("setLimit");
setLimit.addParameter(new Parameter(integerWrapper, "limit"));
setLimit.addBodyLine("this.limit = limit;");
topLevelClass.addMethod(setLimit);

Method getLimit = new Method();
getLimit.setVisibility(JavaVisibility.PUBLIC);
getLimit.setReturnType(integerWrapper);
getLimit.setName("getLimit");
getLimit.addBodyLine("return limit;");
topLevelClass.addMethod(getLimit);

Field offset = new Field();
offset.setName("offset");
offset.setVisibility(JavaVisibility.PRIVATE);
offset.setType(integerWrapper);
topLevelClass.addField(offset);

Method setOffset = new Method();
setOffset.setVisibility(JavaVisibility.PUBLIC);
setOffset.setName("setOffset");
setOffset.addParameter(new Parameter(integerWrapper, "offset"));
setOffset.addBodyLine("this.offset = offset;");
topLevelClass.addMethod(setOffset);

Method getOffset = new Method();
getOffset.setVisibility(JavaVisibility.PUBLIC);
getOffset.setReturnType(integerWrapper);
getOffset.setName("getOffset");
getOffset.addBodyLine("return offset;");
topLevelClass.addMethod(getOffset);

return true;
}

public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable)
{
XmlElement ifLimitNotNullElement = new XmlElement("if");
ifLimitNotNullElement.addAttribute(new Attribute("test", "limit != null"));

XmlElement ifOffsetNotNullElement = new XmlElement("if");
ifOffsetNotNullElement.addAttribute(new Attribute("test", "offset != null"));
ifOffsetNotNullElement.addElement(new org.mybatis.generator.api.dom.xml.TextElement("limit ${offset}, ${limit}"));
ifLimitNotNullElement.addElement(ifOffsetNotNullElement);

XmlElement ifOffsetNullElement = new XmlElement("if");
ifOffsetNullElement.addAttribute(new Attribute("test", "offset == null"));
ifOffsetNullElement.addElement(new org.mybatis.generator.api.dom.xml.TextElement("limit ${limit}"));
ifLimitNotNullElement.addElement(ifOffsetNullElement);

element.addElement(ifLimitNotNullElement);

return true;
}

public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable)
{
return sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
}

You can execute the following command under the directory where the “pom.xml” file is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
mvn mybatis-generator:generate
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building exp 1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.3.4:generate (default-cli) @ exp ---
[INFO] Connecting to the Database
[INFO] Introspecting table sq_slfile.bi_sheet
[INFO] Generating Example class for table bi_sheet
[INFO] Generating Record class for table bi_sheet
[INFO] Generating Mapper Interface for table bi_sheet
[INFO] Generating SQL Map for table bi_sheet
[INFO] Saving file SheetMapper.xml
[INFO] Saving file SheetExample.java
[INFO] Saving file Sheet.java
[INFO] Saving file SheetMapper.java
[WARNING] Existing file /home/user/code/xdata/exp/src/main/java/com/test/exp/orm/model/SheetExample.java was overwritten
[WARNING] Existing file /home/user/code/xdata/exp/src/main/java/com/test/exp/orm/model/Sheet.java was overwritten
[WARNING] Existing file /home/user/code/xdata/exp/src/main/java/com/test/exp/orm/mapper/SheetMapper.java was overwritten
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.879 s
[INFO] Finished at: 2017-05-09T15:18:58+08:00
[INFO] Final Memory: 11M/121M
[INFO] ------------------------------------------------------------------------

Now all the files(Java/XML and etc) are generated automatically.

Comments