MyBatis-Generator最佳實踐


引用地址:http://arccode.net/2015/02/07/MyBatis-Generator%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5/

最近使用MyBatis開發項目,為了快速開發,發現了一個可快速生成mapper類和mapper配置文件及Model的插件-MyBatis-Generator,總結下該插件的使用及最佳實踐.

需求

  1. 為數據庫中的表teacher生成Teacher.java, TeacherMapper.java, TeacherMapper.xml
  2. 由於該插件生成的TeacherMapper.java, TeacherMapper.xml會帶有example, 不希望生成example
  3. 數據庫中的字段寫有注釋, 希望注釋能自動生成在Teacher.java中

實現

實現需求一

1> 建表-teacher

1
2
3
4
5
6
CREATE TABLE `test`.`teacher` (
`id` bigint NOT NULL DEFAULT 0 COMMENT '主鍵id',
`name` varchar(40) NOT NULL DEFAULT '' COMMENT '名稱',
`age` smallint NOT NULL DEFAULT 0 COMMENT '年齡',
PRIMARY KEY (`id`)
) COMMENT= '教師表';

2> 配置properties常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 數據庫驅動jar 路徑
drive.class. path=/Users/arccode/repo/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar
 
# 數據庫連接參數
jdbc. driver=com.mysql.jdbc.Driver
jdbc. url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc. username=mysql
jdbc. password=mysqlpwd
 
# 包路徑配置
model. package=com.arccode.web.model
dao. package=com.arccode.web.dao
xml.mapper. package=com.arccode.web.dao
 
target. project=src/main/java

3> 配置文件-generatorConfig.xml

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
<?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>
<!-- 配置文件路徑 -->
<properties url="${mybatis.generator.generatorConfig.properties}"/>
 
<!--數據庫驅動包路徑 -->
<classPathEntry location="${drive.class.path}"/>
 
<context id="MySQLTables" targetRuntime="MyBatis3">
<!--關閉注釋 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
</commentGenerator>
 
<!--數據庫連接信息 -->
<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}"
password="${jdbc.password}">
</jdbcConnection>
 
<!--生成的model 包路徑 -->
<javaModelGenerator targetPackage="${model.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
 
<!--生成xml mapper文件 路徑 -->
<sqlMapGenerator targetPackage="${xml.mapper.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
</sqlMapGenerator>
 
<!-- 生成的Dao接口 的包路徑 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
</javaClientGenerator>
 
<!--對應數據庫表名 -->
<table tableName="teacher">
 
</table>
</context>
</generatorConfiguration>

4> 運行maven - Run As Maven build

Goals 參數 : mybatis-generator:generate -Dmybatis.generator.overwrite=true

實現需求二

修改配置文件-generatorConfig.xml, 將table標簽修改如下

1
2
3
4
<table tableName="teacher" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>

實現需求三

修改mybatis-generator源碼

位置: mybatis-generator-core/src/main/java/org/mybatis/generator/internal/DefaultCommentGenerator.java

修改該類的方法: addFieldComment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void addFieldComment(Field field,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
 
StringBuilder sb = new StringBuilder();
 
field.addJavaDocLine( "/**"); //$NON-NLS-1$
// field.addJavaDocLine(" * This field was generated by MyBatis Generator."); //$NON-NLS-1$
 
sb. append(" * "); //$NON-NLS-1$
sb. append(introspectedColumn.getRemarks());
sb. append(",所屬表字段為");
sb. append(introspectedTable.getFullyQualifiedTable());
sb. append('.');
sb. append(introspectedColumn.getActualColumnName());
field.addJavaDocLine(sb.toString());
 
// addJavadocTag(field, false);
 
field.addJavaDocLine( " */"); //$NON-NLS-1$
}

如果不想修改源碼, 可以下載mybatis生成中文注釋項目, maven本地安裝后在pom中配置version即可.

使用git克隆github項目(mybatis-generator源項目)

1
2
3
4
5
6
7
8
// 克隆 parent
git clone https://github.com/mybatis/parent.git
// 將該項目安裝到本地maven庫, mybatis-generator依賴於該項目
mvn clean install -Dmaven.test.skip= true
// 克隆 mybatis-generator
git clone https://github.com/mybatis/generator.git
// 將該jar安裝到本地, 之后項目中使用, 時間有點長, 可以喝杯咖啡
mvn clean install -Dmaven.test.skip= true

碰到的問題:

  1. Could not find artifact com.sun:tools:jar:0 at specified path…

平台: Mac

Jdk: 自帶的jdk_1.6.0

解決辦法: 安裝jdk1.7, 該版本帶有tools.jar

最佳實踐

在以上三點需求完成后, 還可做以下修改使得開發更快更敏捷

  1. 配置文件中commentGenerator配置項最好不要設置為不生成注釋,因為這樣帶來的問題是在自動生成的代碼上不會存在@mbggenerated 這樣的標記,這個標記是用來標注這些代碼是代碼生成器生成的,如果關閉了注釋,我們在多次使用mybatis generator重新生成代碼時會導致在已有生成的文件上追加生成重復的內容,導致代碼錯誤,故我建議如果你只生成一次代碼,以后再不用工具生成可以關閉注釋,如果會重復生成就要把注釋開關打開。以下配置參數是關閉時間注釋:
1
2
3
<commentGenerator>
<property name="suppressDate" value="false"/>
</commentGenerator>

Model示例

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
94
95
 
public class Teacher {
 
/**
* 主鍵id,所屬表字段為teacher.id
*/
private Long id;
 
/**
* 名稱,所屬表字段為teacher.name
*/
private String name;
 
/**
* 年齡,所屬表字段為teacher.age
*/
private Short age;
 
/**
* 性別,所屬表字段為teacher.sex
*/
private String sex;
 
/**
* 獲取 主鍵id 字段:teacher.id
*
* @return teacher.id, 主鍵id
*/
public Long getId() {
return id;
}
 
/**
* 設置 主鍵id 字段:teacher.id
*
* @param id teacher.id, 主鍵id
*/
public void setId(Long id) {
this.id = id;
}
 
/**
* 獲取 名稱 字段:teacher.name
*
* @return teacher.name, 名稱
*/
public String getName() {
return name;
}
 
/**
* 設置 名稱 字段:teacher.name
*
* @param name teacher.name, 名稱
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
 
/**
* 獲取 年齡 字段:teacher.age
*
* @return teacher.age, 年齡
*/
public Short getAge() {
return age;
}
 
/**
* 設置 年齡 字段:teacher.age
*
* @param age teacher.age, 年齡
*/
public void setAge(Short age) {
this.age = age;
}
 
/**
* 獲取 性別 字段:teacher.sex
*
* @return teacher.sex, 性別
*/
public String getSex() {
return sex;
}
 
/**
* 設置 性別 字段:teacher.sex
*
* @param sex teacher.sex, 性別
*/
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
}

參考資料

MyBatis Generator使用小記

為Maven指定tools.jar ,解決Missing artifact com.sun:tools:jar:1.5.0錯誤

Maven Frequently Asked Technical Questions

使用 OSC Maven 第三方倉庫

MYBATIS GENEATOR 詳解

mybatisn_generator_cn中文注釋項目


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM