A few days ago, I mentioned a simple example of Mybatis. Today, I recorded a Mybatis reverse engineering (Mybatis Generator), which can quickly generate three layers of dao, mapper, and model.

Official project address of Mybatis Generator: http://www.mybatis.org/generator/

Maven is used here to quickly build:
1. Introduce JAR package: mybatis generator core:

 <!-- Import the jar package of mybatis generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency>

2. Configure MyBatis reverse engineering plug-in in pom.xml:

 <!-- MyBatis auto generation tool plug-in --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin>

3. Create a new mybatis generator configuration file in the resources directory generatorConfig.xml , the file contains comments to change the configuration and table name according to your own situation.

 <? 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> <!-- Import attribute configuration --> <properties resource="db.properties"></properties> <!-- Specify the location of the jdbc drive jar package for a specific database --> <classPathEntry location="${jdbc.driverLocation}"/> <context id="default" targetRuntime="Mybatis3"> <!--  Optional, which is used to control comments when creating classes --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- Database connection of jdbc --> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <!--  Not required, type processor, conversion control between database type and java type --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--  Model generator, used to generate classes containing primary key, record classes, and query Example classes TargetPackage specifies the package name where the generated model is generated TargetProject specifies the path under the project --> <javaModelGenerator targetPackage="com.lcry.web.model" targetProject="src/main/java"> <!--  Whether to allow sub packages, i.e. targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!--  Whether to add a constructor to the model --> <property name="constructorBased" value="true"/> <!--  Whether to trim the data of CHAR type columns --> <property name="trimStrings" value="true"/> <!--  Whether the created Model object is unchangeable means that the generated Model object does not have a setter method, only a construction method --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- The directory where the Mapper mapping file is generated generates the corresponding SqlMap file for each database table --> <sqlMapGenerator targetPackage="com.lcry.web.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!--  Client code to generate easy-to-use code for model objects and XML configuration files Type="ANNOTATEDMAPPER", generating Java Model and annotation based Mapper objects Type="MIXEDMAPER", generating annotation based Java models and corresponding Mapper objects Type="XMLMAPPER", generating SQLMap XML file and independent Mapper interface --> <javaClientGenerator targetPackage="com.lcry.web.dao" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- TableName: the table name is specified DomainObjectName: specifies the name of the entity class --> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> <table tableName="account" domainObjectName="Account" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>

4. Create a new one in the resources directory db.properties

 jdbc.driverLocation=E:\\repository\\mysql\\mysql-connector-java\\5.1.37\\mysql-connector-java-5.1.37.jar jdbc.driverClass=com.mysql.jdbc. Driver jdbc.connectionURL=jdbc: mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf -8 jdbc.username=root jdbc.password=123456

5. Configure maven to build a project. In the project structure, create a new maven, as shown in the following figure. The command is: mybatis-generator:generate -e
 Mybatis from beginner to proficient (II)

6. Run maven.
 Mybatis from beginner to proficient (II)

7. Check whether the generation is successful.
 Mybatis from beginner to proficient (II)

complete! Go and try it now. Eclipse can also use plug-ins. Go and try it now~

22:59:37, December 31, 2018 Update:
Recently, I worked on a final project and found that this reverse function can be simplified a bit, making the generated table more flexible and updated.

1) The SSM project is added in the Spring configuration file first SqlSessionFactory Configuration, add the following configuration to applicationContext.xml In the document.

 <!--  Configure Session Factory SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--  Data source --> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!--  Mybatis configuration file --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--  The dynamic proxy object generated by the scanner that configures mapper in the spring container is automatically registered in the spring container. The bean id is the mapper class name (lowercase first letter) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--  Specify the path of the scanning package, which is the path of the mapper interface. Multiple packages are separated by half commas --> <property name="basePackage" value="com.lcry.dao"/> <!--  Configure sqlSessionFactoryBeanName --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>

2) Create in resources generatorConfig.xml This is the configuration file of mybatis generator.

 <? 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> <!-- Import attribute configuration --> <properties resource="generator.properties"/> <!-- The connection driver fills in its own local er --> <classPathEntry location="E:\repository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar" /> <context id="context1"> <!--  Comments --> <commentGenerator> <property name="suppressAllComments" value="true"/><!--  Whether to uncomment --> <property name="suppressDate" value="true"/> <!--  Generate comment generation timestamp --> </commentGenerator> <jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}"/> <!--  Type conversion --> <javaTypeResolver> <!--  Whether to use bigDecimal, false can automatically convert the following types (Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <javaModelGenerator targetPackage="${modelPackage}" targetProject="${modelProject}"/> <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}"/> <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${mapperProject}" type="XMLMAPPER"/> <!--  If you need to wildcard all tables, just use the% wildcard of SQL --> <table schema="" tableName="${table}" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> </context> </generatorConfiguration>

Please note that the location attribute value of the classPathEntry node above is the location of the local mysql-connector-java.jar, because the connection to the database needs to be driven, we have automatically created the jar package with maven, and find the path of the JAR package in the External Libraries on the left
 Mybatis from beginner to proficient (II)

3) Create generator.properties The configuration file, which stores information about connecting to the database, is used when using the mybatis generator function; In fact, jdbc.properties are used when the system is running. These two pieces of information are similar. If the diagram is convenient, you can combine the two pieces of information into one file. If you write them separately, you can easily plug them in.

 driver=com.mysql.jdbc. Driver url=jdbc: mysql://localhost:3306/javamovie?useUnicode=true&characterEncoding=utf -8 username=root password=lcry #Entity package name and java directory modelPackage=com.lcry.entity modelProject=src/main/java #Sqlmap package name and resources directory (generated *. xml) sqlPackage=mapper sqlProject=src/main/resources #Mapper package name and java directory (generated interface) mapperPackage=com.lcry.dao mapperProject=src/main/java Table=Fill in here to indicate that if you want to generate all, you can use%

ModelPackage is the location where the entity class automatically generated by connecting to the database will be saved, sqlPackage is the location where the generated xml mapping file is saved, mapperPackage is the location where the generated database interface is saved, and table is the name of the table in the database

Finally, use maven to generate!
 Mybatis from beginner to proficient (II)

Reference link:
https://blog.csdn.net/xiaopihai86/article/details/79034079


Attachment: Complete configuration and notes:

 <? 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 "> <!--  Configuration generator --> <generatorConfiguration> <!--  It can be used to load configuration items or configuration files. The configuration items can be referenced in the way of ${propertyKey} in the entire configuration file Resource: Configure the resource loading address. Use resource and MBG to search from classpath, such as com/myproject/generatorConfig.properties Url: configure resources to load geology by using URL, such as file:///C:/myfolder/generatorConfig.properties. Note that only one of the two attributes can be selected; In addition, if mybatis-generator-maven-plugin is used, the properties defined in pom.xml can be directly used in generatorConfig.xml <properties resource="" url="" /> --> <!--  Dependent packages that need to be loaded additionally when MBG is working The location attribute indicates the full path to load the jar/zip package <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <!--  Context: environment for generating a group of objects Id: required, context id, used to prompt when generating errors DefaultModelType: Specify the style of the generated object 1, conditional: similar to hierarchical; 2, flat: All contents (primary key, blob) are generated in one object; 3. Hierarchical: The primary key generates an XXKey object (key class), Blob, etc. generates an object separately, and other simple attributes are in an object (record class) targetRuntime: 1. MyBatis3: The default value, which generates content based on MyBatis3. x or above, including XXXBySample; 2. MyBatis3Simple: similar to MyBatis3, except that XXXBySample is not generated; IntrospectedColumnImpl: fully qualified name of class, used to extend MBG --> <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" > <!--  Automatically identify database keywords. The default is false. If it is set to true, it is based on the keyword list defined in SqlReservedWords; Generally, the default value is reserved. When encountering database keywords (Java keywords), use columnOverride to override --> <property name="autoDelimitKeywords" value="false"/> <!--  Encoding of generated Java file --> <property name="javaFileEncoding" value="UTF-8"/> <!--  Format java code --> <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/> <!--  Format XML code --> <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/> <!--  BeginingDelimiter and endingDelimiter: the symbols used to mark database object names. For example, ORACLE is double quotation marks, and MYSQL defaults to 'back quotation marks; --> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!--  Must have, use this configuration to link the database @TODO: Can I extend it --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc: mysql:///pss " userId="root" password="admin"> <!--  The property attribute can be set here. Each property attribute is set to the configured Driver --> </jdbcConnection> <!--  Java type processor It is used to process types from DB to Java. JavaTypeResolverDefaultImpl is used by default; Note that by default, you will first try to use Integer, Long, Short, etc. to correspond to DECIMAL and NUMERIC data types; --> <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl"> <!--  True: Use BigDecimal to correspond to DECIMAL and NUMERIC data types False: default, scale>0; Length>18: use BigDecimal; scale=0; Length [10,18]: use Long; scale=0; Length [5,9]: use Integer; scale=0; Length<5: use Short; --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--  The java model creator is a required element Responsible for: 1. key class (see defaultModelType in context); 2. Java class; 3. Query class TargetPackage: the package to be placed by the generated class. The real package is controlled by the enableSubPackages attribute; TargetProject: the target project. Specify an existing directory, and the generated content will be placed in the specified directory. If the directory does not exist, MBG will not automatically create a directory --> <javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java"> <!--   for MyBatis3/MyBatis3Simple Automatically create a construction method for each generated class, which includes all fields; Instead of using setters; --> <property name="constructorBased" value="false"/> <!--  Based on the targetPackage, it is regenerated into a layer of packages according to the database schema, and the final generated classes are placed under this package. The default value is false --> <property name="enableSubPackages" value="true"/> <!--  for MyBatis3 / MyBatis3Simple Whether to create an immutable class. If it is true, Then MBG will create a class without setter method and replace it with a class similar to constructorBased --> <property name="immutable" value="false"/> <!--  Set a root object, If this root object is set, the generated keyClass or recordClass will inherit this class; You can override this option in the rootClass attribute of Table Note: If there are the same root class attributes in the key class or record class, MBG will not regenerate these attributes, including: 1. The attribute names and types are the same, and the getter/setter methods are the same; --> <property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/> <!--  Set whether to call trim() method -->on String type field in getter method <property name="trimStrings" value="true"/> </javaModelGenerator> <!--  XML file generator for generating SQL map, Note that after Mybatis3, we can use mapper.xml file+mapper interface (or not use mapper interface), Or only the Mapper interface+Annotation is used. Therefore, if the javaClientGenerator configuration configures the need to generate XML, this element must be configured TargetPackage/targetProject: the same as javaModelGenerator --> <sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources"> <!--  Based on the targetPackage, it is regenerated into a layer of packages according to the database schema, and the final generated classes are placed under this package. The default value is false --> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!--  For mybatis, the Mapper interface is generated. Note that if this element is not configured, the Mapper interface will not be generated by default TargetPackage/targetProject: the same as javaModelGenerator Type: Select how to generate mapper interface (under MyBatis3/MyBatis3Simple): 1. ANNOTATEDMAPPER: It will be created by using the Mapper interface+annotation (SQL is generated in annotation), and the corresponding XML will not be generated; 2. MIXEDMAPER: With mixed configuration, a Mapper interface will be generated and appropriate annotations will be added, but XML will be generated in XML; 3. XMLAPPER: The Mapper interface will be generated, and the interface completely depends on XML; Note that if the context is MyBatis3Simple: only ANNOTATEDMAPPER and XMLAPPER are supported --> <javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java"> <!--  Based on the targetPackage, it is regenerated into a layer of packages according to the database schema, and the final generated classes are placed under this package. The default value is false --> <property name="enableSubPackages" value="true"/> <!--  You can add a parent interface for all generated interfaces, but MBG is only responsible for generating, not checking <property name="rootInterface" value=""/> --> </javaClientGenerator> <!--  Select a table to generate related files. There can be one or more tables, and there must be a table element The selected table will generate the following files: 1. SQL map file 2. Generate a primary key class; 3. Classes of other fields except BLOB and primary key; 4. Classes containing BLOBs; 5. A condition class for user generated dynamic query (selectByExample, deleteByExample), optional; 6. Mapper interface (optional) TableName (required): the table name of the object to be generated; Note: Case sensitivity. Normally, MBG will automatically recognize the case sensitivity of database identifiers. Generally, MBG will Query the data table according to the set schema, catalog or tablename, and follow the following process: 1. If there are spaces in the schema, catalog or tablename, the format set will be queried using the specified case format; 2. Otherwise, if the database identifier is in uppercase, MBG will automatically change the table name to uppercase before searching; 3. Otherwise, if the database identifier is in lowercase, MBG will automatically change the table name to lowercase before searching; 4. Otherwise, use the specified case format to query; In addition, if "" is used to specify the case of database objects when creating tables, even if the database identifier is in uppercase, the table name will be created using the given case; At this time, please set delimitIdentifiers="true" to preserve the case format; Optional: 1. Schema: Database schema; 2. Catalog: the catalog of the database; 3. alias: alias set for the data table. If alias is set, the column name in all the generated SELECT SQL statements will become: alias_actualColumnName 4. domainObjectName: the name of the generated domain class. If not set, directly use the table name as the name of the domain class; It can be set to somepck.domainName, then the domainName class will be automatically put back into somepck package; 5, enableInsert (default true): specifies whether to generate insert statements; 6, enableSelectByPrimaryKey (default true): specifies whether to generate a statement to query objects by primary key (that is, getById or get); 7, enableSelectByExample (default true): MyBatis3Simple is false, which specifies whether to generate dynamic query statements; 8, enableUpdateByPrimaryKey (default true): specifies whether to generate statements that modify objects according to the primary key (that is, update); 9, enableDeleteByPrimaryKey (default true): specifies whether to generate a statement to delete objects according to the primary key (that is, delete); 10, enableDeleteByExample (default true): MyBatis3Simple is false, which specifies whether to generate dynamic deletion statements; 11, enableCountByExample (default true): MyBatis3Simple is false, which specifies whether to generate the total number of dynamic queries (used to query the total number of pages); 12, enableUpdateByExample (default true): MyBatis3Simple is false, which specifies whether to generate dynamic modification statements (only modify non empty properties in objects); 13, modelType: refer to the defaultModelType of the context element, which is equivalent to overwriting; 14, delimitIdentifiers: Refer to the explanation of tableName. Note that the default delimitIdentifiers are double quotes. If a database like MYSQL uses' (back quotes, you also need to set the beginingDelimiter and endingDelimiter attributes of the context) 15, delimitAllColumns: set whether all column names in the generated SQL are quoted with identifiers. The default value is false. DelimitIdentifiers refer to the attribute of context Note that many parameters in the table are a copy of the default attributes of javaModelGenerator, context and other elements; --> <table tableName="userinfo" > <!--  Refer to the constructorBased property of javaModelGenerator --> <property name="constructorBased" value="false"/> <!--  The default value is false. If it is set to true, the table name will not be added with catalog or schema in the generated SQL; --> <property name="ignoreQualifiersAtRuntime" value="false"/> <!--  Refer to the immutable property of javaModelGenerator --> <property name="immutable" value="false"/> <!--  Specify whether to generate only domain classes. If set to true, only domain classes will be generated. If sqlMapGenerator is also configured, only resultMap elements will be generated in the mapper XML file --> <property name="modelOnly" value="false"/> <!--  Refer to the rootClass property of javaModelGenerator <property name="rootClass" value=""/> --> <!--  Refer to the rootInterface property of javaClientGenerator <property name="rootInterface" value=""/> --> <!--  If runtimeCatalog is set, the specified catalog is used instead of the catalog on the table element in the generated SQL <property name="runtimeCatalog" value=""/> --> <!--  If runtimeSchema is set, the specified schema will be used in the generated SQL instead of the schema on the table element <property name="runtimeSchema" value=""/> --> <!--  If runtimeTableName is set, the specified tablename is used instead of tablename on the table element in the generated SQL <property name="runtimeTableName" value=""/> --> <!--  Note that this attribute is only useful for MyBatis3Simple; If the selected runtime is MyBatis3Simple, a SelectAll method will be generated. If selectAllOrderByClause is specified, the specified order condition will be added to the SQL; --> <property name="selectAllOrderByClause" value="age desc,username asc"/> <!--  If set to true, the generated model class will directly use the name of the column itself instead of the hump naming method, such as BORN_DATE. The generated attribute name is BORN_DATE, not bornDate --> <property name="useActualColumnNames" value="false"/> <!--  The generatedKey is used to generate the method for generating the primary key, If this element is set, MBG will generate a correct<selectKey>element in the generated<insert>element, which is optional Column: column name of the primary key; SqlStatement: The selectKey statement to be generated has the following options: Cloudscape: SQL equivalent to selectKey: VALUES IDENTITY_VAL_LOCAL() DB2: The SQL equivalent to selectKey is: VALUES IDENTITY_VAL_LOCAL() DB2_MF: The SQL equivalent to selectKey is: SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1 Derby: The SQL equivalent to selectKey is: VALUES IDENTITY_VAL_LOCAL() HSQLDB: The SQL equivalent to selectKey is: CALL IDENTITY() Informix: The SQL equivalent to selectKey is: select dbinfo ('sqlca. sqlerrd1 ') from systables where tabid=1 MySql: The SQL equivalent to selectKey is: SELECT LAST_INSERT_ID() SqlServer: The SQL equivalent to selectKey is: SELECT SCOPE_IDENTITY() SYBASE: The SQL equivalent to selectKey is: SELECT @ @ IDENTITY JDBC: equivalent to adding useGeneratedKeys="true" and keyProperty attributes on the generated insert element <generatedKey column="" sqlStatement=""/> --> <!--  This element renames the column name before calculating the object attribute name according to the column name in the table, which is very suitable for when all columns in the table have a common prefix string, For example, the column names are CUST_ID, CUST_NAME, CUST_EMAIL, CUST_ADDRESS, etc; Then you can set searchString to "^ CUST_" and replace it with blank, then the attribute name in the generated Customer object is not CustId, custName, etc., are first replaced with ID, NAME, EMAIL, and then become attributes: id, name, email; Note that MBG uses java. util. regex Matcher.replaceAll to replace searchString and replaceString, If columnOverride element is used, this attribute is invalid; <columnRenamingRule searchString="" replaceString=""/> --> <!--  Used to modify the attributes of a column in the table. MBG will use the modified column to generate the attributes of the domain; Column: the column name to be reset; Note that there can be multiple columnOverride elements in a table element~ --> <columnOverride column="username"> <!--  Use the property attribute to specify the attribute name to be generated by the column --> <property name="property" value="userName"/> <!--  JavaType is used to specify the attribute type of the generated domain, using the fully qualified name of the type <property name="javaType" value=""/> --> <!--  JdbcType is used to specify the JDBC type of the column <property name="jdbcType" value=""/> --> <!--  TypeHandler is used to specify the TypeHandler used by this column. If you want to specify it, configure the fully qualified name of the type handler Note that the typeHandler in mybatis-config.xml will not be generated in mybatis Only parameter descriptions like where id=# {id, jdbcType=BIGINT, typeHandler=com. _520it. mybatis. MyTypeHandler} will be generated <property name="jdbcType" value=""/> --> <!--  Refer to the delimitAllColumns configuration of the table element. The default value is false <property name="delimitedColumnName" value=""/> --> </columnOverride> <!--  IgnoreColumn sets a column ignored by MGB. If the column is changed, the column will not appear in the generated domain or SQL Column: specifies the name of the column to be ignored; DelimitedColumnName: refer to the delimiteAllColumns configuration of the table element. The default value is false Note that a table element can have multiple ignoreColumn elements <ignoreColumn column="deptId" delimitedColumnName=""/> --> </table> </context> </generatorConfiguration>