介紹
Mybatis Generator(MBG)是Mybatis的一個代碼生成工具。MBG解決了對數(shù)據(jù)庫操作有最大影響的一些CRUD操作,很大程度上提升開發(fā)效率。如果需要聯(lián)合查詢?nèi)匀恍枰謱憇ql。相信很多人都聽說過微服務(wù),各個微服務(wù)之間是松耦合的。每個微服務(wù)僅關(guān)注于完成一件任務(wù)并很好地完成該任務(wù)。在一個微服務(wù)的開發(fā)過程中很可能只關(guān)注對單表的操作。所以MBG在開發(fā)過程中可以快速的生成代碼提升開發(fā)效率。
本文將說到在springboot的項目中如何去配置(XML形式和Java配置類形式)和使用MBG以及MBG生成代碼的兩種方式(XML形式和注解形式),在springboot中更推薦去使用注解的形式。
MBG配置
1.添加依賴
1
2
3
4
5
|
< dependency > < groupId >org.mybatis.generator</ groupId > < artifactId >mybatis-generator-core</ artifactId > < version >1.3.5</ version > </ dependency > |
2.XML配置
配置示例:在新建springboot項目的根目錄下創(chuàng)建mbg.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
46
47
48
49
|
<? 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 > < context id = "DB2Tables" targetRuntime = "MyBatis3" > < commentGenerator > <!-- 是否自動去除生成注釋 true 不生成--> < property name = "suppressAllComments" value = "true" /> <!--生成的注釋包含時間戳--> <!-- <property name="suppressDate" value="true"/> --> </ commentGenerator > <!-- 數(shù)據(jù)庫連接信息 --> < jdbcConnection driverClass = "com.mysql.jdbc.Driver" connectionURL = "jdbc:mysql://localhost:3306/definesys" userId = "root" password = "welcome1" > </ jdbcConnection > <!-- 默認(rèn)false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> < javaTypeResolver > < property name = "forceBigDecimals" value = "true" /> </ javaTypeResolver > <!-- 實體類 bean 帶有g(shù)et和set方法的bean --> < javaModelGenerator targetPackage = "com.mgb.domain" targetProject = "src/main/java" > < property name = "enableSubPackages" value = "true" /> < property name = "trimStrings" value = "true" /> </ javaModelGenerator > <!-- sql語句相關(guān)的xml或者注解的生成包路徑 --> < sqlMapGenerator targetPackage = "com.mgb.mapper" targetProject = "src/main/java" > < property name = "enableSubPackages" value = "true" /> </ sqlMapGenerator > <!-- 生成的接口所在的位置 注解type="ANNOTATEDMAPPER" xml type="XMLMAPPER" --> < javaClientGenerator type = "ANNOTATEDMAPPER" targetPackage = "com.mgb.dao" targetProject = "src/main/java" > < property name = "enableSubPackages" value = "true" /> </ javaClientGenerator > < table tableName = "user_info" enableCountByExample = "true" enableUpdateByExample = "true" enableDeleteByExample = "true" enableSelectByExample = "true" selectByExampleQueryId = "true" > < property name = "constructorBased" value = "false" /> <!-- 數(shù)據(jù)庫表主鍵 --> < generatedKey column = "id" sqlStatement = "JDBC" identity = "true" /> </ table > </ context > </ generatorConfiguration > |
配置詳解
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
|
<? 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 > <!-- 可以用于加載配置項或者配置文件,在整個配置文件中就可以使用${propertyKey}的方式來引用配置項 resource:配置資源加載地址,使用resource,MBG從classpath開始找,比如com/myproject/generatorConfig.properties url:配置資源加載地質(zhì),使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties. 注意,兩個屬性只能選址一個; 另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定義的properties都可以直接在generatorConfig.xml中使用 <properties resource="" url="" /> --> <!-- 在MBG工作的時候,需要額外加載的依賴包 location屬性指明加載jar/zip包的全路徑 <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <!-- context:生成一組對象的環(huán)境 id:必選,上下文id,用于在生成錯誤時提示 defaultModelType:指定生成對象的樣式 1,conditional:類似hierarchical; 2,flat:所有內(nèi)容(主鍵,blob)等全部生成在一個對象中; 3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其他簡單屬性在一個對象中(record class) targetRuntime: 1,MyBatis3:默認(rèn)的值,生成基于MyBatis3.x以上版本的內(nèi)容,包括XXXBySample; 2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample; introspectedColumnImpl:類全限定名,用于擴(kuò)展MBG --> < context id = "mysql" defaultModelType = "hierarchical" targetRuntime = "MyBatis3Simple" > <!-- 自動識別數(shù)據(jù)庫關(guān)鍵字,默認(rèn)false,如果設(shè)置為true,根據(jù)SqlReservedWords中定義的關(guān)鍵字列表; 一般保留默認(rèn)值,遇到數(shù)據(jù)庫關(guān)鍵字(Java關(guān)鍵字),使用columnOverride覆蓋 --> < property name = "autoDelimitKeywords" value = "false" /> <!-- 生成的Java文件的編碼 --> < property name = "javaFileEncoding" value = "UTF-8" /> <!-- 格式化java代碼 --> < property name = "javaFormatter" value = "org.mybatis.generator.api.dom.DefaultJavaFormatter" /> <!-- 格式化XML代碼 --> < property name = "xmlFormatter" value = "org.mybatis.generator.api.dom.DefaultXmlFormatter" /> <!-- beginningDelimiter和endingDelimiter:指明數(shù)據(jù)庫的用于標(biāo)記數(shù)據(jù)庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認(rèn)是`反引號; --> < property name = "beginningDelimiter" value = "`" /> < property name = "endingDelimiter" value = "`" /> <!-- 必須要有的,使用這個配置鏈接數(shù)據(jù)庫 @TODO:是否可以擴(kuò)展 --> < jdbcConnection driver connectionURL = "jdbc:mysql:///pss" userId = "root" password = "admin" > <!-- 這里面可以設(shè)置property屬性,每一個property屬性都設(shè)置到配置的Driver上 --> </ jdbcConnection > <!-- java類型處理器 用于處理DB中的類型到Java中的類型,默認(rèn)使用JavaTypeResolverDefaultImpl; 注意一點,默認(rèn)會先嘗試使用Integer,Long,Short等來對應(yīng)DECIMAL和 NUMERIC數(shù)據(jù)類型; --> < javaTypeResolver type = "org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl" > <!-- true:使用BigDecimal對應(yīng)DECIMAL和 NUMERIC數(shù)據(jù)類型 false:默認(rèn), scale>0;length>18:使用BigDecimal; scale=0;length[10,18]:使用Long; scale=0;length[5,9]:使用Integer; scale=0;length<5:使用Short; --> < property name = "forceBigDecimals" value = "false" /> </ javaTypeResolver > <!-- java模型創(chuàng)建器,是必須要的元素 負(fù)責(zé):1,key類(見context的defaultModelType);2,java類;3,查詢類 targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制; targetProject:目標(biāo)項目,指定一個存在的目錄下,生成的內(nèi)容會放到指定目錄中,如果目錄不存在,MBG不會自動建目錄 --> < javaModelGenerator targetPackage = "com._520it.mybatis.domain" targetProject = "src/main/java" > <!-- for MyBatis3/MyBatis3Simple 自動為每一個生成的類創(chuàng)建一個構(gòu)造方法,構(gòu)造方法包含了所有的field;而不是使用setter; --> < property name = "constructorBased" value = "false" /> <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個package下,默認(rèn)為false --> < property name = "enableSubPackages" value = "true" /> <!-- for MyBatis3 / MyBatis3Simple 是否創(chuàng)建一個不可變的類,如果為true, 那么MBG會創(chuàng)建一個沒有setter方法的類,取而代之的是類似constructorBased的類 --> < property name = "immutable" value = "false" /> <!-- 設(shè)置一個根對象, 如果設(shè)置了這個根對象,那么生成的keyClass或者recordClass會繼承這個類;在Table的rootClass屬性中可以覆蓋該選項 注意:如果在key class或者record class中有root class相同的屬性,MBG就不會重新生成這些屬性了,包括: 1,屬性名相同,類型相同,有相同的getter/setter方法; --> < property name = "rootClass" value = "com._520it.mybatis.domain.BaseDomain" /> <!-- 設(shè)置是否在getter方法中,對String類型字段調(diào)用trim()方法 --> < property name = "trimStrings" value = "true" /> </ javaModelGenerator > <!-- 生成SQL map的XML文件生成器, 注意,在Mybatis3之后,我們可以使用mapper.xml文件+Mapper接口(或者不用mapper接口), 或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的話,這個元素就必須配置 targetPackage/targetProject:同javaModelGenerator --> < sqlMapGenerator targetPackage = "com._520it.mybatis.mapper" targetProject = "src/main/resources" > <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個package下,默認(rèn)為false --> < property name = "enableSubPackages" value = "true" /> </ sqlMapGenerator > <!-- 對于mybatis來說,即生成Mapper接口,注意,如果沒有配置該元素,那么默認(rèn)不會生成Mapper接口 targetPackage/targetProject:同javaModelGenerator type:選擇怎么生成mapper接口(在MyBatis3/MyBatis3Simple下): 1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式創(chuàng)建(SQL生成在annotation中),不會生成對應(yīng)的XML; 2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,并適當(dāng)添加合適的Annotation,但是XML會生成在XML中; 3,XMLMAPPER:會生成Mapper接口,接口完全依賴XML; 注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER --> < javaClientGenerator targetPackage = "com._520it.mybatis.mapper" type = "ANNOTATEDMAPPER" targetProject = "src/main/java" > <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個package下,默認(rèn)為false --> < property name = "enableSubPackages" value = "true" /> <!-- 可以為所有生成的接口添加一個父接口,但是MBG只負(fù)責(zé)生成,不負(fù)責(zé)檢查 <property name="rootInterface" value=""/> --> </ javaClientGenerator > <!-- 選擇一個table來生成相關(guān)文件,可以有一個或多個table,必須要有table元素 選擇的table會生成一下文件: 1,SQL map文件 2,生成一個主鍵類; 3,除了BLOB和主鍵的其他字段的類; 4,包含BLOB的類; 5,一個用戶生成動態(tài)查詢的條件類(selectByExample, deleteByExample),可選; 6,Mapper接口(可選) tableName(必要):要生成對象的表名; 注意:大小寫敏感問題。正常情況下,MBG會自動的去識別數(shù)據(jù)庫標(biāo)識符的大小寫敏感度,在一般情況下,MBG會 根據(jù)設(shè)置的schema,catalog或tablename去查詢數(shù)據(jù)表,按照下面的流程: 1,如果schema,catalog或tablename中有空格,那么設(shè)置的是什么格式,就精確的使用指定的大小寫格式去查詢; 2,否則,如果數(shù)據(jù)庫的標(biāo)識符使用大寫的,那么MBG自動把表名變成大寫再查找; 3,否則,如果數(shù)據(jù)庫的標(biāo)識符使用小寫的,那么MBG自動把表名變成小寫再查找; 4,否則,使用指定的大小寫格式查詢; 另外的,如果在創(chuàng)建表的時候,使用的""把數(shù)據(jù)庫對象規(guī)定大小寫,就算數(shù)據(jù)庫標(biāo)識符是使用的大寫,在這種情況下也會使用給定的大小寫來創(chuàng)建表名; 這個時候,請設(shè)置delimitIdentifiers="true"即可保留大小寫格式; 可選: 1,schema:數(shù)據(jù)庫的schema; 2,catalog:數(shù)據(jù)庫的catalog; 3,alias:為數(shù)據(jù)表設(shè)置的別名,如果設(shè)置了alias,那么生成的所有的SELECT SQL語句中,列名會變成:alias_actualColumnName 4,domainObjectName:生成的domain類的名字,如果不設(shè)置,直接使用表名作為domain類的名字;可以設(shè)置為somepck.domainName,那么會自動把domainName類再放到somepck包里面; 5,enableInsert(默認(rèn)true):指定是否生成insert語句; 6,enableSelectByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵查詢對象的語句(就是getById或get); 7,enableSelectByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動態(tài)查詢語句; 8,enableUpdateByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵修改對象的語句(即update); 9,enableDeleteByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵刪除對象的語句(即delete); 10,enableDeleteByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動態(tài)刪除語句; 11,enableCountByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動態(tài)查詢總條數(shù)語句(用于分頁的總條數(shù)查詢); 12,enableUpdateByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動態(tài)修改語句(只修改對象中不為空的屬性); 13,modelType:參考context元素的defaultModelType,相當(dāng)于覆蓋; 14,delimitIdentifiers:參考tableName的解釋,注意,默認(rèn)的delimitIdentifiers是雙引號,如果類似MYSQL這樣的數(shù)據(jù)庫,使用的是`(反引號,那么還需要設(shè)置context的beginningDelimiter和endingDelimiter屬性) 15,delimitAllColumns:設(shè)置是否所有生成的SQL中的列名都使用標(biāo)識符引起來。默認(rèn)為false,delimitIdentifiers參考context的屬性 注意,table里面很多參數(shù)都是對javaModelGenerator,context等元素的默認(rèn)屬性的一個復(fù)寫; --> < table tableName = "userinfo" > <!-- 參考 javaModelGenerator 的 constructorBased屬性--> < property name = "constructorBased" value = "false" /> <!-- 默認(rèn)為false,如果設(shè)置為true,在生成的SQL中,table名字不會加上catalog或schema; --> < property name = "ignoreQualifiersAtRuntime" value = "false" /> <!-- 參考 javaModelGenerator 的 immutable 屬性 --> < property name = "immutable" value = "false" /> <!-- 指定是否只生成domain類,如果設(shè)置為true,只生成domain類,如果還配置了sqlMapGenerator,那么在mapper XML文件中,只生成resultMap元素 --> < property name = "modelOnly" value = "false" /> <!-- 參考 javaModelGenerator 的 rootClass 屬性 <property name="rootClass" value=""/> --> <!-- 參考javaClientGenerator 的 rootInterface 屬性 <property name="rootInterface" value=""/> --> <!-- 如果設(shè)置了runtimeCatalog,那么在生成的SQL中,使用該指定的catalog,而不是table元素上的catalog <property name="runtimeCatalog" value=""/> --> <!-- 如果設(shè)置了runtimeSchema,那么在生成的SQL中,使用該指定的schema,而不是table元素上的schema <property name="runtimeSchema" value=""/> --> <!-- 如果設(shè)置了runtimeTableName,那么在生成的SQL中,使用該指定的tablename,而不是table元素上的tablename <property name="runtimeTableName" value=""/> --> <!-- 注意,該屬性只針對MyBatis3Simple有用; 如果選擇的runtime是MyBatis3Simple,那么會生成一個SelectAll方法,如果指定了selectAllOrderByClause,那么會在該SQL中添加指定的這個order條件; --> < property name = "selectAllOrderByClause" value = "age desc,username asc" /> <!-- 如果設(shè)置為true,生成的model類會直接使用column本身的名字,而不會再使用駝峰命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate --> < property name = "useActualColumnNames" value = "false" /> <!-- generatedKey用于生成生成主鍵的方法, 如果設(shè)置了該元素,MBG會在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選 column:主鍵的列名; sqlStatement:要生成的selectKey語句,有以下可選項: Cloudscape:相當(dāng)于selectKey的SQL為: VALUES IDENTITY_VAL_LOCAL() DB2 :相當(dāng)于selectKey的SQL為: VALUES IDENTITY_VAL_LOCAL() DB2_MF :相當(dāng)于selectKey的SQL為:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1 Derby :相當(dāng)于selectKey的SQL為:VALUES IDENTITY_VAL_LOCAL() HSQLDB :相當(dāng)于selectKey的SQL為:CALL IDENTITY() Informix :相當(dāng)于selectKey的SQL為:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1 MySql :相當(dāng)于selectKey的SQL為:SELECT LAST_INSERT_ID() SqlServer :相當(dāng)于selectKey的SQL為:SELECT SCOPE_IDENTITY() SYBASE :相當(dāng)于selectKey的SQL為:SELECT @@IDENTITY JDBC :相當(dāng)于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性 <generatedKey column="" sqlStatement=""/> --> <!-- 該元素會在根據(jù)表中列名計算對象屬性名之前先重命名列名,非常適合用于表中的列都有公用的前綴字符串的時候, 比如列名為:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等; 那么就可以設(shè)置searchString為"^CUST_",并使用空白替換,那么生成的Customer對象中的屬性名稱就不是 custId,custName等,而是先被替換為ID,NAME,EMAIL,然后變成屬性:id,name,email; 注意,MBG是使用java.util.regex.Matcher.replaceAll來替換searchString和replaceString的, 如果使用了columnOverride元素,該屬性無效; <columnRenamingRule searchString="" replaceString=""/> --> <!-- 用來修改表中某個列的屬性,MBG會使用修改后的列來生成domain的屬性; column:要重新設(shè)置的列名; 注意,一個table元素中可以有多個columnOverride元素哈~ --> <!-- 指定類型 --> < columnOverride column = "RECORD_DATE" jdbcType = "TIMESTAMP" /> < columnOverride column = "username" > <!-- 使用property屬性來指定列要生成的屬性名稱 --> < property name = "property" value = "userName" /> <!-- javaType用于指定生成的domain的屬性類型,使用類型的全限定名 <property name="javaType" value=""/> --> <!-- jdbcType用于指定該列的JDBC類型 <property name="jdbcType" value=""/> --> <!-- typeHandler 用于指定該列使用到的TypeHandler,如果要指定,配置類型處理器的全限定名 注意,mybatis中,不會生成到mybatis-config.xml中的typeHandler 只會生成類似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的參數(shù)描述 <property name="jdbcType" value=""/> --> <!-- 參考table元素的delimitAllColumns配置,默認(rèn)為false <property name="delimitedColumnName" value=""/> --> </ columnOverride > <!-- ignoreColumn設(shè)置一個MGB忽略的列,如果設(shè)置了改列,那么在生成的domain中,生成的SQL中,都不會有該列出現(xiàn) column:指定要忽略的列的名字; delimitedColumnName:參考table元素的delimitAllColumns配置,默認(rèn)為false 注意,一個table元素中可以有多個ignoreColumn元素 <ignoreColumn column="deptId" delimitedColumnName=""/> --> </ table > </ context > </ generatorConfiguration > |
生成代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class TestMGB { public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException { List<String> warnings = new ArrayList<String>(); boolean overwrite= true ; File configFile= new File( "mgb.xml" ); ConfigurationParser cp= new ConfigurationParser(warnings); Configuration config=cp.parseConfiguration(configFile); DefaultShellCallback callback= new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator= new MyBatisGenerator(config,callback,warnings); myBatisGenerator.generate( null ); } } |
3.Java配置示例
基于Java的配置是和上面的XML配置是相對應(yīng)的。直接運行該示例即可生成數(shù)據(jù)表對于的pojo,mapper接口和一個sqlprovider 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
94
95
96
97
98
99
100
101
102
103
104
105
106
|
package com.mgb.test; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.CommentGeneratorConfiguration; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.Context; import org.mybatis.generator.config.JDBCConnectionConfiguration; import org.mybatis.generator.config.JavaClientGeneratorConfiguration; import org.mybatis.generator.config.JavaModelGeneratorConfiguration; import org.mybatis.generator.config.JavaTypeResolverConfiguration; import org.mybatis.generator.config.ModelType; import org.mybatis.generator.config.PluginConfiguration; import org.mybatis.generator.config.SqlMapGeneratorConfiguration; import org.mybatis.generator.config.TableConfiguration; import org.mybatis.generator.internal.DefaultShellCallback; public class MGBConfig { public static void main(String[] args) throws Exception{ //配置xml配置項 List<String> warnings = new ArrayList<String>(); boolean overwrite = true ; Configuration config = new Configuration(); Context context = new Context(ModelType.CONDITIONAL); context.setTargetRuntime( "MyBatis3" ); context.setId( "defaultContext" ); //自動識別數(shù)據(jù)庫關(guān)鍵字,默認(rèn)false,如果設(shè)置為true, //根據(jù)SqlReservedWords中定義的關(guān)鍵字列表;一般保留默認(rèn)值,遇到數(shù)據(jù)庫關(guān)鍵字(Java關(guān)鍵字), //使用columnOverride覆蓋 context.addProperty( "autoDelimitKeywords" , "true" ); //生成的Java文件的編碼 context.addProperty( "javaFileEncoding" , "utf-8" ); context.addProperty( "beginningDelimiter" , "`" ); context.addProperty( "endingDelimiter" , "`" ); //格式化java代碼 context.addProperty( "javaFormatter" , "org.mybatis.generator.api.dom.DefaultJavaFormatter" ); //格式化xml代碼 context.addProperty( "xmlFormatter" , "org.mybatis.generator.api.dom.DefaultXmlFormatter" ); //格式化信息 PluginConfiguration pluginConfiguration = new PluginConfiguration(); pluginConfiguration.setConfigurationType( "org.mybatis.generator.plugins.SerializablePlugin" ); pluginConfiguration.setConfigurationType( "org.mybatis.generator.plugins.ToStringPlugin" ); context.addPluginConfiguration(pluginConfiguration); //設(shè)置是否去除生成注釋 CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration(); commentGeneratorConfiguration.addProperty( "suppressAllComments" , "true" ); //commentGeneratorConfiguration.addProperty("suppressDate","true"); context.setCommentGeneratorConfiguration(commentGeneratorConfiguration); //設(shè)置連接數(shù)據(jù)庫 JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration(); jdbcConnectionConfiguration.setDriverClass( "com.mysql.jdbc.Driver" ); jdbcConnectionConfiguration.setConnectionURL( "jdbc:mysql://localhost:3306/definesys" ); jdbcConnectionConfiguration.setPassword( "welcome1" ); jdbcConnectionConfiguration.setUserId( "root" ); context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration); JavaTypeResolverConfiguration javaTypeResolverConfiguration = new JavaTypeResolverConfiguration(); //是否使用bigDecimal, false可自動轉(zhuǎn)化以下類型(Long, Integer, Short, etc.) javaTypeResolverConfiguration.addProperty( "forceBigDecimals" , "false" ); context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration); //生成實體類的地址 JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration(); javaModelGeneratorConfiguration.setTargetPackage( "com.mgb.domain" ); javaModelGeneratorConfiguration.setTargetProject( "src/main/java" ); javaModelGeneratorConfiguration.addProperty( "enableSubPackages" , "true" ); javaModelGeneratorConfiguration.addProperty( "trimStrings" , "true" ); context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration); //生成的xml的地址 SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration(); sqlMapGeneratorConfiguration.setTargetProject( "src/main/java" ); sqlMapGeneratorConfiguration.setTargetPackage( "com.mgb.mapper" ); sqlMapGeneratorConfiguration.addProperty( "enableSubPackages" , "true" ); context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration); //生成注解接口 JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration(); javaClientGeneratorConfiguration.setTargetPackage( "com.mgb.dao" ); javaClientGeneratorConfiguration.setTargetProject( "src/main/java" ); //注解形式 ANNOTATEDMAPPER xml形式 XMLMAPPER javaClientGeneratorConfiguration.setConfigurationType( "ANNOTATEDMAPPER" ); javaClientGeneratorConfiguration.addProperty( "enableSubPackages" , "true" ); context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration); TableConfiguration tableConfiguration = new TableConfiguration(context); tableConfiguration.setTableName( "user_info" ); tableConfiguration.setCountByExampleStatementEnabled( true ); tableConfiguration.setUpdateByExampleStatementEnabled( true ); tableConfiguration.setDeleteByExampleStatementEnabled( true ); tableConfiguration.setInsertStatementEnabled( true ); tableConfiguration.setDeleteByPrimaryKeyStatementEnabled( true ); context.addTableConfiguration(tableConfiguration); config.addContext(context); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate( null ); } } |
使用
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
|
package com.mgb.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mgb.dao.UserInfoMapper; import com.mgb.domain.UserInfo; import com.mgb.domain.UserInfoExample; @Service public class UserService { @Autowired private UserInfoMapper userInfoMapper; /** * 按姓名查詢 * @param name * @return */ public List<UserInfo> getUserByName(String name){ UserInfoExample uerInfoExample= new UserInfoExample(); uerInfoExample.createCriteria().andNameEqualTo(name); return userInfoMapper.selectByExample(uerInfoExample); } /** * 有條件的insert * @param userInfo * @return */ public Integer addUser(UserInfo userInfo) { return userInfoMapper.insertSelective(userInfo); } /** * 根據(jù)ID更新用戶信息 * @param userInfo * @return */ public Integer updateUser(UserInfo userInfo) { return userInfoMapper.updateByPrimaryKey(userInfo); } /** * 根據(jù)ID刪除用戶 * @param id * @return */ public Integer deleteUserById(Integer id) { return userInfoMapper.deleteByPrimaryKey(id); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000017007028