Mybatis reverse generation

Mybatis reverse generation


brief introduction

Reverse engineering literally means reverse generation engineering. Like hibernate, mybatis also has its own reverse engineering tools. I haven't done the reverse generation of hibernate

When using reverse engineering, it should be noted that the relationship between tables cannot be mapped
In other words, the reverse engineering of mybatis generates single table operations

1:mybatis reverse engineering development document:
http://www.mybatis.org/genera...



There are several ways to use reverse engineering to generate code. Here is a simple java program generation

Get ready

0. A simple spring boot project generated quickly Online

1. Test database



create database if not exists test00 default character set utf8 collate utf8_general_ci;

use test00;

create table citizen(
    id int(11) not null auto_increment comment 'citizen ID',
    citizenName varchar(20) not null comment 'Citizen name',
    PRIMARY KEY (`id`),
    KEY `cid` (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

The dependence of pom

<dependency>
            <groupId>io.github.orange1438</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

Reverse generation of core configurationgeneratorconfiguration.xml


<?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>
    <!--Database driven -->
    <!-- If IDE(eclipse perhaps idea)Imported in the project jar Package, then there is no need to configure jar The absolute path of the package <classPathEntry        location="e:/project/mybatis/lib/mysql-connector-java-5.0.8-bin.jar"/> -->

    <context id="MysqlContext" targetRuntime="MyBatis3Simple"
        defaultModelType="flat">

        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="false" />
        </commentGenerator>

        <!--Database link address account password -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost/test00" userId="root"
            password="root">
        </jdbcConnection>

        <!-- default false,hold JDBC DECIMAL and NUMERIC Type resolves to Integer,by true Shi Ba JDBC DECIMAL
            //And NUMERIC types resolve to Java. Math. BigDecimal -- >
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--Generate entity class storage location -->
        <javaModelGenerator
            targetPackage="cn.example.demo.po" targetProject="src/main/java">
        </javaModelGenerator>

        <!--Generating mapping xml File storage location -->
        <sqlMapGenerator targetPackage="mapper"
            targetProject="src/main/resources">
        </sqlMapGenerator>

        <!--generate Dao Class storage location -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="cn.example.demo.mapper" targetProject="src/main/java">
        </javaClientGenerator>

        <!--Generate corresponding table and class name -->
        <!--Generate corresponding table and class name,One thing to remember is that reverse engineering can't generate relationships,Only single table operation can be generated -->
        <table tableName="citizen" domainObjectName="Citizen" />

    </context>

</generatorConfiguration>

Java code

package cn.example.demo.util;

import java.io.InputStream;
import java.util.ArrayList;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * Reverse generation
 *
 * @author gzh
 *
 */
public class ReverseGeneratorFunction {
    public static void main(String[] args) throws Exception {
        ArrayList<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        
        //Filename: generatorConfiguration.xml
        InputStream is = ReverseGeneratorFunction.class.getClassLoader().getResource("generatorConfiguration.xml")
                .openStream();

        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);

        is.close();
        System.out.println("Code generation succeeded, refresh project, view file");

    }

}

Run the main method to generate entity class / mapping xml file / DAO method, and the results are as follows:

Entity class

/* https://github.com/orange1438 */
package cn.example.demo.po;

public class Citizen {
    /** 
     * Citizen ID
     */ 
    private Integer id;

    /** 
     * Citizen name
     */ 
    private String citizenname;

    /** 
     * Get citizen ID citizen.id
     * @return Citizen ID
     */
    public Integer getId() {
        return id;
    }

    /** 
     * Set citizen ID citizen.id
     * @param id Citizen ID
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /** 
     * Get citizen.citizen name
     * @return Citizen name
     */
    public String getCitizenname() {
        return citizenname;
    }

    /** 
     * Set citizen name citizen.citizen name
     * @param citizenname Citizen name
     */
    public void setCitizenname(String citizenname) {
        this.citizenname = citizenname;
    }
}
CitizenMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.example.demo.mapper.CitizenDAO">

    <resultMap id="BaseResultMap"
        type="cn.example.demo.po.Citizen">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="citizenName" jdbcType="VARCHAR"
            property="citizenname" />
    </resultMap>
    
    <delete id="deleteByPrimaryKey"
        parameterType="java.lang.Integer">
        delete from citizen
        where id = #{id,jdbcType=INTEGER}
    </delete>
    
    <insert id="insert" parameterType="cn.example.demo.po.Citizen">
        insert into citizen (id, citizenName)
        values (#{id,jdbcType=INTEGER}, #{citizenname,jdbcType=VARCHAR})
    </insert>
    
    <update id="updateByPrimaryKey"
        parameterType="cn.example.demo.po.Citizen">
        update citizen
        set citizenName = #{citizenname,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
    </update>
    
    <select id="selectByPrimaryKey"
        parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select id, citizenName
        from citizen
        where id = #{id,jdbcType=INTEGER}
    </select>
    
    <select id="selectAll" resultMap="BaseResultMap">
        select id, citizenName
        from citizen
    </select>
    
</mapper>

DAO interface

/* https://github.com/orange1438 */
package cn.example.demo.mapper;

import cn.example.demo.po.Citizen;
import java.util.List;

public interface CitizenDAO {
    /** 
     * Delete by ID
     * @param id Primary key ID
     * @return Return the number of successful deletion
     */
    int deleteByPrimaryKey(Integer id);

    /** 
     * Add all fields of the object
     * @param record Insert field object (must have ID)
     * @return Return the number of successful additions
     */
    int insert(Citizen record);

    /** 
     * Query by ID
     * @param id Primary key ID
     * @return Return the result of the query
     */
    Citizen selectByPrimaryKey(Integer id);

    /** 
     *
     * @return Return the result of the query
     */
    List<Citizen> selectAll();

    /** 
     * Modify all fields according to ID (ID must be included)
     * @param record Modify field object (must have ID)
     * @return Returns the number of successful updates
     */
    int updateByPrimaryKey(Citizen record);
}

The MySQL connector Java connection dependency version in pom must be equal to or higher than the current MySQL database version. If the version is lower, an error will be reported. If the version is higher, an exception will be reported. However, the reverse generation is still successful

Keywords: Java Mybatis xml Database

Added by jason97673 on Sun, 03 Nov 2019 20:43:32 +0200