Spring cloud + mybatis (oracle) reverse engineering generates code automatically

1, What is reverse engineering?


Usually our development process, in addition to the construction of the system framework. What's more, CRUD can't avoid dealing with the database because of the code logic of adding, deleting, modifying and querying CRUD. The common database operations are insert (add), update (modify), select (query), delete (delete); the traditional database level development involves the following processes:

1. Establish database DB connection (existing table)

2. Entity class / POJO/Mapper.xml

3. Add, delete, modify and query procedures

Among them, the second step: entity class / POJO/XML, etc.; they are all hand written code and xml files, which are forward engineering.

2, Why reverse engineering?


As mentioned in the first section: forward engineering, manual code entity class / POJO/Mapper.xml, etc., many operations are repetitive and redundant. For example, entity class is actually a mapping of database table. It lists the table fields one by one and sets getter/setter methods for program use. pojo, select, update, delete, and insert methods are all the same, except for different methods and parameters. XML is the connection point of SQL statement integration and database interaction; for the same project, database connection is the same, project path is the same, etc.

If entity classes, pojo, xml, etc. can be generated automatically, then a lot of repetitive human workload can be reduced, and the machine can generate them automatically. When the database table has a large amount of operation, it will save a lot of time.

3, Operation steps of MyBatis reverse engineering in Spring

 

  • Maven add dependency
  • generatorConfig.xml configuration
  • Database connection configuration, entity class / POJO/XML generation path
  • Specify database tables
  • main method for automatic generation of java class

1. Maven depends on, including ojdbc database connection, mybatis support and spring mybatis plug-in.

SpringBoot's support for MyBatis plug-in:

       

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>


Automatically generate mybatis generator core dependency Introduction (core):

            

<plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>


2. generatorConfig.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
 
    <classPathEntry
        location="C:\Users\Administrator\.m2\repository\com\oracle\ojdbc6\11.1.0.7.0\ojdbc6-11.1.0.7.0.jar" />
    <context id="context1"> 
        <property name="javaFileEncoding" value="UTF-8" />
        <commentGenerator type="com.**nks.e**s.CustomCommentGenerator" >
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
 
        <jdbcConnection connectionURL="jdbc:oracle:thin:@//1**.20.19.2**:1521/p**y"
            driverClass="oracle.jdbc.driver.OracleDriver" password="***#123"
            userId="**s">
            <!-- in the light of oracle data base -->
            <property name="remarksReporting" value="true"></property>
        </jdbcConnection>
 
 
        <javaModelGenerator targetPackage="com.**nks.**ps.pas.tmp"
            targetProject="src\main\java\com\**links\**ps\pas\tmp" />
 
        <sqlMapGenerator targetPackage="com.**links.**ps.pas.tmp"
            targetProject="src\main\java\com\**links\**ps\pas\tmp" />
 
        <javaClientGenerator targetPackage="com.**links.**ps.pas.tmp"
            targetProject="src\main\java\com\**links\**ps\pas\tmp" type="XMLMAPPER" />
 
 
        <table tableName="CUM_WITHDRAW_COUNT_RECORD" domainObjectName="WithdrawCountRecord"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>


3. class file of main method entry automatically generated by CustomCommentGenerator

package com.**links.**ps;
 
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.DefaultShellCallback;
 
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
public class CustomCommentGenerator extends DefaultCommentGenerator {
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        // Add field comment
        field.addJavaDocLine("/**"); 
        if (introspectedColumn.getRemarks() != null) {
            field.addJavaDocLine(" * " + introspectedColumn.getRemarks());
        }
         // addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }
    
    
    public static void main(String[] args) throws Exception {
        try {
            List<String> warnings = new ArrayList();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
 
}


After the above steps are completed, the code can be generated automatically without starting the project.

Right click the CustomCommentGenerator class and select run or debug

 

Next, the program automatically generates the entity class, POJO, mapper.xml required by the specified table

As follows:

Entity class with comments

In this way, the whole process is completed.

Note: the generation path here is the temporary path folder src\main\java\com\**links\**ps\pas\tmp created by the owner himself. If there are batch tables that need to be generated automatically, just configure multiple tables in the generatorConfig.xml file.

 


        <table tableName="tableName***" domainObjectName="pojoName***"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
......


The reverse engineering of MyBatis brings us great convenience. It's a technology that developers must master and share here. I think it's helpful to give a compliment and forward it.

 


Pay attention to official account: the big vision of procedure

Feel helpful to you, pay attention to blog and official account. From time to time, we will share the latest cutting-edge technology framework and common technologies of bat plant, and from time to time, we will share live lectures of Daniel in the industry and obtain video courseware materials.
 

Tags: Programming Mybatis xml Database Java

Posted on Sun, 17 May 2020 05:19:48 -0400 by osnewbie2004