This article will introduce the use of spring boot frame , introduce mybatis-generator plug-in unit , combination tk.mybatis Automatic generation Mapper and Entity A complete set of processes , Including the most important step and fill pit .

    One 、 infrastructure                                                                                                                                                     

  • Demonstration database

  • initial spring boot project

Use IDEA Create a springboot project

     Two 、 Protagonist on stage                                                                                                                              

1. stay pom.xml Introduction in mybatis-generator plug-in unit . Be careful , What I'm using here is tk.mybatis. So we need to introduce the corresponding dependency . And add mapper Interface

1 <dependency>
2 <groupId>tk.mybatis</groupId>
3 <artifactId>mapper-spring-boot-starter</artifactId>
4 <version>2.0.2</version>
5 </dependency>
1 package com.tk;
2
3 import tk.mybatis.mapper.common.Mapper;
4 import tk.mybatis.mapper.common.MySqlMapper;
5
6 public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
7 }
configurationFile The node is configured to generate mapper、entity Required profile , So we need to add gengeatorConfig.xml The configuration file .
 1
2 <plugin>
3 <groupId>org.mybatis.generator</groupId>
4 <artifactId>mybatis-generator-maven-plugin</artifactId>
5 <version>1.3.5</version>
6 <configuration>
7 <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
8 <overwrite>true</overwrite>
9 <verbose>true</verbose>
10 </configuration>
11 <dependencies>
12 <dependency>
13 <groupId>mysql</groupId>
14 <artifactId>mysql-connector-java</artifactId>
15 <version>${mysql.version}</version>
16 </dependency>
17 <dependency>
18 <groupId>tk.mybatis</groupId>
19 <artifactId>mapper</artifactId>
20 <version>3.4.4</version>
21 </dependency>
22 </dependencies>
23 </plugin>

2. add to generatorConfig.xml file . The file location should be the same as pom.xml The paths configured in are consistent . About the meaning and purpose of each configuration node of the configuration file , There is a detailed explanation at the end of the article .

The configuration file was introduced at the beginning jdbc.properties Database connection profile , So you need to be in resources Add the configuration file under the folder .

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE generatorConfiguration
3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
5
6 <generatorConfiguration>
7 <!-- Introduce database connection configuration -->
8 <properties resource="jdbc.properties"/>
9
10 <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
11 <property name="beginningDelimiter" value="`"/>
12 <property name="endingDelimiter" value="`"/>
13
14 <!-- To configure tk.mybatis plug-in unit -->
15 <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
16 <property name="mappers" value="com.tk.MyMapper"/>
17 </plugin>
18
19 <!-- Configure database connections -->
20 <jdbcConnection
21 driverClass="${jdbc.driverClass}"
22 connectionURL="${jdbc.connectionURL}"
23 userId="${jdbc.username}"
24 password="${jdbc.password}">
25 </jdbcConnection>
26
27 <!-- Configure the storage path of entity class -->
28 <javaModelGenerator targetPackage="com.senda.hello.spring.boot.entity" targetProject="src/main/java"/>
29
30 <!-- To configure XML Storage path -->
31 <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
32
33 <!-- To configure DAO Storage path -->
34 <javaClientGenerator
35 targetPackage="com.senda.hello.spring.boot.mapper"
36 targetProject="src/main/java"
37 type="XMLMAPPER"/>
38
39 <!-- Configuration needs to specify the generated database and tables ,% For all tables -->
40 <table catalog="dbtest" tableName="%">
41 <!-- mysql To configure -->
42 <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
43 </table>
44 </context>
45 </generatorConfiguration>

3. add to jdbc.properties Database connection profile . It should be noted that mysql8.0 after ,driverClass The package name has changed .

1 jdbc.driverClass=com.mysql.jdbc.Driver
2 #8.0 after :jdbc.driverClass=com.mysql.cj.jdbc.Driver
3 jdbc.connectionURL=jdbc:mysql://127.0.0.1:3306/dbtest?useUnicode=true&characterEncoding=utf-8&useSSL=false
4 jdbc.username=root
5 jdbc.password=root

4. After the above steps , The engineering structure is shown in the figure below .

5. everything , An automated build , start-up . double-click mybatis-generator Under plug-in mybatis-generator:generate Instructions , Start automatic build . After building , More in the project entity、dao、mapper, It's so beautiful !

                 

6. Now check the database , See if this thing works . Here I use Alibaba's druid, So we need to introduce dependency .

1 <dependency>
2 <groupId>com.alibaba</groupId>
3 <artifactId>druid-spring-boot-starter</artifactId>
4 <version>1.1.10</version>
5 </dependency>
6 <dependency>
7 <groupId>mysql</groupId>
8 <artifactId>mysql-connector-java</artifactId>
9 </dependency>

And in application.yml Add the relevant configuration to the configuration file , Include druid and mybatis.

 1 spring:
2 datasource:
3 druid:
4 url: jdbc:mysql://127.0.0.1:3306/dbtest?useUnicode=true&characterEncoding=utf-8&useSSL=false
5 username: root
6 password: root
7 initial-size: 1
8 min-idle: 1
9 max-active: 20
10 test-on-borrow: true
11 driver-class-name: com.mysql.jdbc.Driver
12 #MySQL 8.x: driver-class-name: com.mysql.cj.jdbc.Driver
13
14 mybatis:
15 type-aliases-package: com.senda.hello.spring.boot.mybatis.entity
16 mapper-locations: classpath:mapper/*.xml

You also need to add MapperScan annotation , To specify Dao The location of . Note that the introduction here is tk Under bag MapperScan.

 1 package com.senda.hello.spring.boot.mybatis;
2
3 import org.springframework.boot.SpringApplication;
4 import org.springframework.boot.autoconfigure.SpringBootApplication;
5 import tk.mybatis.spring.annotation.MapperScan;
6
7 @SpringBootApplication
8 @MapperScan(basePackages = "com.senda.hello.spring.boot.mapper")
9 public class HelloSpringBootMybatisApplication {
10
11 public static void main(String[] args) {
12 SpringApplication.run(HelloSpringBootMybatisApplication.class, args);
13 }
14
15 }

Write a test method , Have a good time ! Pay attention to SpringBootTest The comments indicate the test class , To load the configuration file .

 1 package com.senda.hello.spring.boot.mybatis;
2
3 import com.senda.hello.spring.boot.mapper.TbUserMapper;
4 import com.senda.hello.spring.boot.entity.TbUser;
5 import org.junit.Test;
6 import org.junit.runner.RunWith;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.boot.test.context.SpringBootTest;
9 import org.springframework.test.context.junit4.SpringRunner;
10
11 import java.util.List;
12
13 @RunWith(SpringRunner.class)
14 @SpringBootTest(classes = HelloSpringBootMybatisApplication.class)
15 public class HelloSpringBootMybatisApplicationTests {
16
17 @Autowired
18 private TbUserMapper userMapper;
19
20 @Test
21 public void testSelect() {
22 List<TbUser> userList = userMapper.selectAll();
23 for (TbUser user : userList)
24 System.out.println(user.getLoginname());
25 }
26
27 }

Run test class ,Oops! Wrong report !!! Find out SQL The sentence is wrong , There is a dot between the database and table names . Fat four . It's been a long time , You tell me it doesn't work ?

org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.tb_user' at line 1
### The error may exist in com/senda/hello/spring/boot/mapper/TbUserMapper.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT uid,loginname,loginpass,email,status,activationCode FROM dbtest..tb_user
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.tb_user' at line 1
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.tb_user' at line 1

Have a problem , To solve it !!! Open generated TbUser Entity class , We were surprised to find that ,table My name is a little more . Quickly delete , Run the test method again .bingo, Perfect operation , Problem solved .

    

3、 ... and 、 To analyze problems                                                                                                                                                     

Is the problem really solved ? The real project , Dozens of times 、 Hundreds of watches , Do you want to delete them one by one ? It's such a mature plug-in , Would you be bothered with such a low-level mistake ? because Entity、Dao、mapper Are all based on generatorConfig.xml File to generate . therefore , It's only possible that the configuration file is mismatched . So where is the wrong match ?

1. First , We need to know ,database、schema、catalog The connection and difference of the three .

according to SQL Standard interpretation , stay SQL In the environment Catalog and Schema All belong to abstract concepts , They can be understood as a hierarchy in a container or database object namespace , The main Used to solve naming conflicts . Conceptually , A database system contains multiple Catalog, Every Catalog There are more than one Schema, And each Schema It also contains many numbers Database objects ( surface 、 View 、 Field etc. ), Conversely, a database object must belong to a Schema, And the Schema It must belong to a Catalog, In this way, we can get the fully qualified name of the database object to solve the problem of naming conflict ; For example, the fully qualified name of a database object table can be expressed as :Catalog name .Schema name . The name of the table . here Another thing to note is ,SQL The standard does not require that the fully qualified name of each database object be unique , Just like a domain name , If you like , Every IP Addresses can have multiple domain names .

MySQL 5.5 That's what the official document says :

CREATE DATABASE creates a database with the given name.
To use this statement, you need the CREATE privilege for the database.
CREATE SCHEMA is a synonym for CREATE DATABASE.

[ translate ]
CREATE DATABASE Create a database with the given name .
You need to have a database of CREATE Permission to use this statement .
CREATE SCHEMA yes CREATE DATABASE A pronoun for .

in other words , stay MySQL in ,schema and database It's the same thing . and MySQL And does not support catalog, therefore , What we usually see MySQL The fully qualified name of the database object table is :database.table.

The common database pairs are given below catalog、schema Support for :

supplier

Catalog Support

Schema Support

Oracle

I won't support it

Oracle User ID

MySQL

I won't support it

Database name

MS SQL Server

Database name

The object belongs to the principal name ,2005 It's starting to change

DB2

When specifying a database object ,Catalog Part omitted

Catalog The name of the owner

Sybase

Database name

Database owner name

Informix

I won't support it

Unwanted

PointBase

I won't support it

Database name

2. Okay , Back to our problems . With the above background knowledge , We can quickly locate generatorConfig.xml There's something wrong with the file configuration . stay table node , We've configured catalog The attribute is database name . Now you know at a glance that the configuration is wrong , Out of thin air , Delete the attribute .

          

For the sake of insurance , We still have to be in jdbcConnection Add attributes to the node , State that the current database does not support catalog.

<property name="nullCatalogMeansCurrent" value="true"/>

3. Now let's rerun the command , Generate Entity、Dao、mapper, After successful generation , have a look TbUser Of table annotation , It's the name of the watch . Test the class at run time , perfect !!! What else , Just blossom and it's done .

              

Four 、 appendix                                                                                                                                                       

complete generatorConfig.xml Configuration and attribute annotation .

  1 <xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE generatorConfiguration
3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
5 <!-- Configuration Generator -->
6 <generatorConfiguration>
7 <!-- Can be used to load configuration items or profiles , Available in the entire configuration file ${propertyKey} To reference configuration items
8 resource: Configure resource load address , Use resource,MBG from classpath Start looking for , such as com/myproject/generatorConfig.properties
9 url: Allocation of resources loading geology , Use URL The way , such as file:///C:/myfolder/generatorConfig.properties.
10 Be careful , Only one location can be selected for two attributes ;
11
12 in addition , If used mybatis-generator-maven-plugin, So in pom.xml As defined in properties Can be directly in generatorConfig.xml Use in
13 <properties resource="" url="" />
14 -->
15
16 <!-- stay MBG At work , Dependent packages that need to be extra loaded
17 location Property indicates load jar/zip Full path of package
18 <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
19 -->
20
21 <!--
22 context: Environment for generating a set of objects
23 id: Mandatory , Context id, Used to prompt when generating errors
24 defaultModelType: Specifies the style of the build object
25 1,conditional: similar hierarchical;
26 2,flat: All contents ( Primary key ,blob) Wait for all to be generated in one object ;
27 3,hierarchical: Generate a primary key XXKey object (key class),Blob Wait for an object to be generated separately , Other simple properties in one object (record class)
28 targetRuntime:
29 1,MyBatis3: Default value , Generation based MyBatis3.x Contents of the above version , Include XXXBySample;
30 2,MyBatis3Simple: similar MyBatis3, Just don't generate XXXBySample;
31 introspectedColumnImpl: Class full name , Used to extend MBG
32 -->
33 <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >
34
35 <!-- Automatically identify database keywords , Default false, If set to true, according to SqlReservedWords List of keywords defined in ;
36 Generally keep the default value , Database key encountered (Java keyword ), Use columnOverride Cover
37 -->
38 <property name="autoDelimitKeywords" value="false"/>
39 <!-- Generated Java Coding of documents -->
40 <property name="javaFileEncoding" value="UTF-8"/>
41 <!-- format java Code -->
42 <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
43 <!-- format XML Code -->
44 <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
45
46 <!-- beginningDelimiter and endingDelimiter: Indicates the symbol used to mark the database object name for the database , such as ORACLE It's double quotes ,MYSQL The default is ` The quotation marks ; -->
47 <property name="beginningDelimiter" value="`"/>
48 <property name="endingDelimiter" value="`"/>
49
50 <!-- Must have , Use this configuration to link the database
51 @TODO: Whether it can be extended
52 -->
53 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql:///pss" userId="root" password="admin">
54 <!-- It can be set here property attribute , every last property Properties are set to the configured Driver On -->
55 </jdbcConnection>
56
57 <!-- java Type processor
58 Used for processing DB Types in to Java The type of , By default JavaTypeResolverDefaultImpl;
59 Be careful. , Try to use it first by default Integer,Long,Short Equal correspondence DECIMAL and NUMERIC data type ;
60 -->
61 <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
62 <!--
63 true: Use BigDecimal Corresponding DECIMAL and NUMERIC data type
64 false: Default ,
65 scale>0;length>18: Use BigDecimal;
66 scale=0;length[10,18]: Use Long;
67 scale=0;length[5,9]: Use Integer;
68 scale=0;length<5: Use Short;
69 -->
70 <property name="forceBigDecimals" value="false"/>
71 </javaTypeResolver>
72
73
74 <!-- java Model creator , Is a required element
75 be responsible for :1,key class ( see context Of defaultModelType);2,java class ;3, Query class
76 targetPackage: Generated class package to put , Real package enableSubPackages Attribute control ;
77 targetProject: Target project , Specify an existing directory , The generated content will be placed in the specified directory , If the directory does not exist ,MBG Directory will not be created automatically
78 -->
79 <javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java">
80 <!-- for MyBatis3/MyBatis3Simple
81 Automatically create a constructor for each generated class , The constructor contains all field; Instead of using setter;
82 -->
83 <property name="constructorBased" value="false"/>
84
85 <!-- stay targetPackage On the basis of , According to the schema Regenerate into a layer package, The resulting class is placed here package Next , The default is false -->
86 <property name="enableSubPackages" value="true"/>
87
88 <!-- for MyBatis3 / MyBatis3Simple
89 Whether to create an immutable class , If true,
90 that MBG Will create a no setter Class of method , Instead, it's similar constructorBased Class
91 -->
92 <property name="immutable" value="false"/>
93
94 <!-- Set a root object ,
95 If the root object is set , So the generated keyClass perhaps recordClass Will inherit this class ; stay Table Of rootClass You can override this option in the
96 Be careful : If in key class perhaps record class There is root class Same property ,MBG You won't regenerate these properties , Include :
97 1, Same property name , The same type , Have the same getter/setter Method ;
98 -->
99 <property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>
100
101 <!-- Is the setting getter In the method , Yes String Type field call trim() Method -->
102 <property name="trimStrings" value="true"/>
103 </javaModelGenerator>
104
105
106 <!-- Generate SQL map Of XML File generator ,
107 Be careful , stay Mybatis3 after , We can use mapper.xml file +Mapper Interface ( Or not mapper Interface ),
108 Or just use Mapper Interface +Annotation, therefore , If javaClientGenerator Build required is configured in the configuration XML Words , This element must be configured
109 targetPackage/targetProject: Same as javaModelGenerator
110 -->
111 <sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources">
112 <!-- stay targetPackage On the basis of , According to the schema Regenerate into a layer package, The resulting class is placed here package Next , The default is false -->
113 <property name="enableSubPackages" value="true"/>
114 </sqlMapGenerator>
115
116
117 <!-- about mybatis Come on , Generation Mapper Interface , Be careful , If the element is not configured , Then it will not be generated by default Mapper Interface
118 targetPackage/targetProject: Same as javaModelGenerator
119 type: Choose how to generate mapper Interface ( stay MyBatis3/MyBatis3Simple Next ):
120 1,ANNOTATEDMAPPER: Will generate usage Mapper Interface +Annotation The way to create (SQL Generated in annotation in ), No corresponding XML;
121 2,MIXEDMAPPER: Use mixed configuration , Will generate Mapper Interface , And add appropriate Annotation, however XML Will be generated in XML in ;
122 3,XMLMAPPER: Will generate Mapper Interface , Interface completely dependent XML;
123 Be careful , If context yes MyBatis3Simple: Only support ANNOTATEDMAPPER and XMLMAPPER
124 -->
125 <javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java">
126 <!-- stay targetPackage On the basis of , According to the schema Regenerate into a layer package, The resulting class is placed here package Next , The default is false -->
127 <property name="enableSubPackages" value="true"/>
128
129 <!-- You can add a parent interface for all generated interfaces , however MBG Build only , Not responsible for inspection
130 <property name="rootInterface" value=""/>
131 -->
132 </javaClientGenerator>
133
134 <!-- Select a table To generate related files , There can be one or more table, There must be table Elements
135 Select the table It will generate the following files :
136 1,SQL map file
137 2, Generate a primary key class ;
138 3, except BLOB And other fields of the primary key ;
139 4, contain BLOB Class ;
140 5, A condition class for user generated dynamic query (selectByExample, deleteByExample), Optional ;
141 6,Mapper Interface ( Optional )
142
143 tableName( necessary ): Table name of the object to build ;
144 Be careful : Case sensitive issues . Under normal circumstances ,MBG The case sensitivity of database identifier will be automatically identified , In general ,MBG Meeting
145 By setup schema,catalog or tablename To query the data table , Follow the procedure below :
146 1, If schema,catalog or tablename Spaces in , What is the format set , Exactly use the specified case format to query ;
147 2, otherwise , If the database identifier uses uppercase , that MBG Automatically change the table name to uppercase and search again ;
148 3, otherwise , If the database identifier uses lowercase , that MBG Automatically change the table name to lowercase and search again ;
149 4, otherwise , Query using the specified case format ;
150 additional , When creating a table , The use of "" Case database objects , Even if the database identifier is capitalized , In this case, the table name will also be created with the given case ;
151 This is the time , Please set up delimitIdentifiers="true" To preserve case formatting ;
152
153 Optional :
154 1,schema: Database schema;
155 2,catalog: Database catalog;
156 3,alias: Alias set for data table , If set alias, Then all the generated SELECT SQL In the sentence , The column name will become :alias_actualColumnName
157 4,domainObjectName: Generated domain The name of the class , If not set , Use table name directly as domain The name of the class ; It can be set to somepck.domainName, Then it will automatically domainName Class re placed somepck Inside the package ;
158 5,enableInsert( Default true): Specify whether to generate insert sentence ;
159 6,enableSelectByPrimaryKey( Default true): Specifies whether to generate statements that query objects by primary key ( Namely getById or get);
160 7,enableSelectByExample( Default true):MyBatis3Simple by false, Specifies whether dynamic query statements are generated ;
161 8,enableUpdateByPrimaryKey( Default true): Specifies whether to generate statements that modify objects according to the primary key ( namely update);
162 9,enableDeleteByPrimaryKey( Default true): Specifies whether to generate a statement to delete objects by primary key ( namely delete);
163 10,enableDeleteByExample( Default true):MyBatis3Simple by false, Specifies whether to generate a dynamic delete statement ;
164 11,enableCountByExample( Default true):MyBatis3Simple by false, Specifies whether to generate a dynamic query total number statement ( Total number of queries for paging );
165 12,enableUpdateByExample( Default true):MyBatis3Simple by false, Specifies whether dynamic modification statements are generated ( Modify only non empty properties in the object );
166 13,modelType: Reference resources context Elemental defaultModelType, Equivalent to coverage ;
167 14,delimitIdentifiers: Reference resources tableName The explanation of , Be careful , default delimitIdentifiers Double quotation marks. , If similar MYSQL Such a database , It uses `( The quotation marks , Then you need to set context Of beginningDelimiter and endingDelimiter attribute )
168 15,delimitAllColumns: Set whether all generated SQL The column names in are quoted by identifiers . The default is false,delimitIdentifiers Reference resources context Properties of
169
170 Be careful ,table Many of the parameters are right javaModelGenerator,context A copy of the default attribute of the equal element ;
171 -->
172 <table tableName="userinfo" >
173
174 <!-- Reference resources javaModelGenerator Of constructorBased attribute -->
175 <property name="constructorBased" value="false"/>
176
177 <!-- The default is false, If set to true, In the generated SQL in ,table Name will not be added catalog or schema; -->
178 <property name="ignoreQualifiersAtRuntime" value="false"/>
179
180 <!-- Reference resources javaModelGenerator Of immutable attribute -->
181 <property name="immutable" value="false"/>
182
183 <!-- Specify whether to build only domain class , If set to true, Generate only domain class , If it is also configured sqlMapGenerator, So in mapper XML In file , Generate only resultMap Elements -->
184 <property name="modelOnly" value="false"/>
185
186 <!-- Reference resources javaModelGenerator Of rootClass attribute
187 <property name="rootClass" value=""/>
188 -->
189
190 <!-- Reference resources javaClientGenerator Of rootInterface attribute
191 <property name="rootInterface" value=""/>
192 -->
193
194 <!-- If set runtimeCatalog, So the SQL in , Use the specified catalog, instead of table Element catalog
195 <property name="runtimeCatalog" value=""/>
196 -->
197
198 <!-- If set runtimeSchema, So the SQL in , Use the specified schema, instead of table Element schema
199 <property name="runtimeSchema" value=""/>
200 -->
201
202 <!-- If set runtimeTableName, So the SQL in , Use the specified tablename, instead of table Element tablename
203 <property name="runtimeTableName" value=""/>
204 -->
205
206 <!-- Be careful , This attribute is only for MyBatis3Simple Useful ;
207 If selected runtime yes MyBatis3Simple, So it's going to generate one SelectAll Method , If you specify selectAllOrderByClause, Then we will SQL Add the specified order Conditions ;
208 -->
209 <property name="selectAllOrderByClause" value="age desc,username asc"/>
210
211 <!-- If set to true, Generated model Class will be used directly column Its own name , Instead of hump naming , such as BORN_DATE, The generated property name is BORN_DATE, Not really. bornDate -->
212 <property name="useActualColumnNames" value="false"/>
213
214
215 <!-- generatedKey Method for generating primary key ,
216 If the element is set ,MBG Will be generated in <insert> Element to generate a correct <selectKey> Elements , This element is optional
217 column: Column name of primary key ;
218 sqlStatement: To generate the selectKey sentence , The following options are available :
219 Cloudscape: amount to selectKey Of SQL by : VALUES IDENTITY_VAL_LOCAL()
220 DB2 : amount to selectKey Of SQL by : VALUES IDENTITY_VAL_LOCAL()
221 DB2_MF : amount to selectKey Of SQL by :SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
222 Derby : amount to selectKey Of SQL by :VALUES IDENTITY_VAL_LOCAL()
223 HSQLDB : amount to selectKey Of SQL by :CALL IDENTITY()
224 Informix : amount to selectKey Of SQL by :select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
225 MySql : amount to selectKey Of SQL by :SELECT LAST_INSERT_ID()
226 SqlServer : amount to selectKey Of SQL by :SELECT SCOPE_IDENTITY()
227 SYBASE : amount to selectKey Of SQL by :SELECT @@IDENTITY
228 JDBC : Equivalent to the insert Add on element useGeneratedKeys="true" and keyProperty attribute
229 <generatedKey column="" sqlStatement=""/>
230 -->
231
232 <!--
233 This element renames the column name before calculating the object property name based on the column name in the table , It is very suitable when all columns in the table have a common prefix string ,
234 For example, the column name is :CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS etc. ;
235 Then you can set searchString by "^CUST_", And replace with blank , So the generated Customer The property name in the object is not
236 custId,custName etc. , It's replaced with ID,NAME,EMAIL, And then it becomes an attribute :id,name,email;
237
238 Be careful ,MBG It's using java.util.regex.Matcher.replaceAll To replace searchString and replaceString Of ,
239 If used columnOverride Elements , The property is invalid ;
240
241 <columnRenamingRule searchString="" replaceString=""/>
242 -->
243
244
245 <!-- Used to modify the properties of a column in a table ,MBG The modified column will be used to generate domain Properties of ;
246 column: Column name to reset ;
247 Be careful , One table Element can have more than one columnOverride Yuan ha ~
248 -->
249 <columnOverride column="username">
250 <!-- Use property Property to specify the name of the property the column will generate -->
251 <property name="property" value="userName"/>
252
253 <!-- javaType Used to specify the generated domain Property type of , Fully qualified name of usage type
254 <property name="javaType" value=""/>
255 -->
256
257 <!-- jdbcType Used to specify the JDBC type
258 <property name="jdbcType" value=""/>
259 -->
260
261 <!-- typeHandler Used to specify the TypeHandler, If you want to specify , Fully qualified name of the configuration type processor
262 Be careful ,mybatis in , Not generated to mybatis-config.xml Medium typeHandler
263 Only similar :where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler} Parameter description of
264 <property name="jdbcType" value=""/>
265 -->
266
267 <!-- Reference resources table Elemental delimitAllColumns To configure , The default is false
268 <property name="delimitedColumnName" value=""/>
269 -->
270 </columnOverride>
271
272 <!-- ignoreColumn Set up a MGB Ignored columns , If column change is set , So the domain in , Generated SQL in , This column will not appear
273 column: Specifies the name of the column to ignore ;
274 delimitedColumnName: Reference resources table Elemental delimitAllColumns To configure , The default is false
275
276 Be careful , One table Element can have more than one ignoreColumn Elements
277 <ignoreColumn column="deptId" delimitedColumnName=""/>
278 -->
279 </table>
280
281 </context>
282
283 </generatorConfiguration>

[ End ]

The content is reproduced from :https://www.cnblogs.com/little-rain/p/11063410.html

Use mybatis-generator Plug in Integration tk.mybatis Automatic generation mapper More articles about

  1. Eclipse MyBatis Generator Plug in installation

    Catalog Eclipse MyBatis Generator Plug in installation Eclipse MyBatis Generator Plug in installation 1. Get into Eclipse Marketplace [Help] -> ...

  2. Use mybatis generator plug-in unit , Automatic generation dao、dto、mapper Wait for the documents

    mybatis generator Introduce mybatis generator Chinese document http://mbg.cndocs.tk/ MyBatis Generator (MBG) It's a Mybatis Generation of ...

  3. Use mybatis-generator Plug in Integration tk.mybatis Automatic generation mapper Two or three things

    This article will introduce the use of spring boot frame , introduce mybatis-generator plug-in unit , combination tk.mybatis Automatic generation Mapper and Entity A complete set of processes , Including the most important step and fill pit .     ...

  4. Use Mybatis Generator The plug-in automatically generates the mapping file (cmd Unable to enter file ,dns The server has no authority on the region ) Have a problem

            Use Mybatis Genertor Plug in automatically generates MyBatis The required DAO Interface , Entity model class ,Mapping The mapping file , Assign the generated code to the project .     There's a command line ,Eclipse insert ...

  5. Eclipse Use mybatis generator Plug in automatically generates code

    Eclipse Use mybatis generator Plug in automatically generates code label : mybatis 2016-12-07 15:10 5247 Human reading Comment on (0) Collection report .embody{ paddin ...

  6. SpringBoot The generality of the framework mapper plug-in unit (tk.mybatis)

    One .Tkmybatis The benefits of Tkmybatis Is in mybatis The framework provides a lot of tools , Make development more efficient . This plug-in encapsulates a lot of what we need to use sql sentence , However, this plug-in is encapsulated by calling it ...

  7. mybatis generator Plug in installation and use

    Now? Mybatis especially popular , But in the development, we often write entity classes and configuration files , Would it be particularly annoying , So we can use Mybatis Code generation plug-in to generate this part of the code : 1, open eclipse, Click on Help>Softwar ...

  8. maven(18)-mybatis generator plug-in unit

     generator The role of Use mybatis frame , When starting a project or modifying a database , The corresponding one is JAVA Write some data model files in the project ,DAO, mapping XML Other configuration , And the function of this plug-in is to automatically generate these files , To save big ...

  9. Mybatis-Generator_ Study _02_ Use Mapper A dedicated MyBatis Generator plug-in unit

    See source code :https://github.com/shirayner/tk-mybatis-generator One . The main points of Two . Concrete realization 1. Project structure 2. To configure pm.xml <?xml versio ...

  10. Mybatis Generator Plug ins and PageHelper Use

    lately , Begin to contact web Project development , Project use springboot and mybatis, I used to think that entity classes in the development process ,mybatis Of xml Files need to be created manually . My colleague recommended that Mybatis Generato ...

Random recommendation

  1. [ original ] Make it for the first time JQueryUI plug-in unit -Timeline time axis

    characteristic : 1. Support more left and right scrolling , Drag left and right . 2. The time axis can be displayed up and down . 3. Supports two modes of smooth scrolling / Drag the . 4. Line compression ( You can set whether to turn on or not in subsequent versions , The uploaded code doesn't have this function ). 5. Support hov ...

  2. *HDU1151 Bipartite graph

    Air Raid Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Su ...

  3. Web Performance test parameters

    1. Preface Recently introduced in the project keyless, It needs to be tested web Performance impact . common web The test tools are ab.siege.http_load etc. . I use it Apache Of ab Testing tools . In the test web Before performance , First ...

  4. MM How to change the material evaluation class in

    stay SAP MM Module , I. materials XXX , From the original outsourcing , It's made in the factory : The evaluation class has also changed from the original 7901 Change it to :7900 : notes : Evaluation of materials , Corresponding to some accounts , For what happened , Data generated , Record it in the corresponding account number : To change ...

  5. [html][ turn ] Return to the top code

    Transferred to :http://jingyan.baidu.com/article/7082dc1ca6b928e40a89bd1a.html One . Use HTML It's the simplest anchor mark But the only drawback is that the style is not very good , Meeting ...

  6. JSON Medium parse and Stringify Method

    JSON.parse(str)   Parse a string into an object var str = '{"name":"huangxiaojian","age":&q ...

  7. A1013. Battle Over Cities

    It is vitally important to have all the cities connected by highways in a war. If a city is occupied ...

  8. Kafka Technology insider Book notes ( 5、 ... and ) The coordinator —— The coordinator processes the request

    Consumer clients use “ The consumer's coordinator target ”( ConsumerCoordinator ) To represent all request processing related to the server coordinator node , Like heartbeat request . Get and commit the offset of the partition ( Automatically submit tasks ). send out “ Join group request ” ...

  9. Source control tools ( Next )-SVN Directory structure

    It contains base64string Images cause too many characters , Reject display

  10. The first 7 Chapter Linux File and directory management

    Directory and path Relative path and absolute path Operation related to directory . Represents this layer directory .. On behalf of the upper directory - Represents the previous working directory ~ representative " Current user identity " Folder in which ~account representative accou ...