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:

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

The dependence of pom


Reverse generation of core configurationgeneratorconfiguration.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-// MyBatis Generator Configuration 1.0//EN"
    <!--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"

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

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

        <!-- 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 -- >
            <property name="forceBigDecimals" value="false" />

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

        <!--Generating mapping xml File storage location -->
        <sqlMapGenerator targetPackage="mapper"

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

        <!--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" />



Java code

package cn.example.demo.util;

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

        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);

        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

/* */
package cn.example.demo.po;

public class Citizen {
     * Citizen ID
    private Integer id;

     * Citizen name
    private String citizenname;

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

     * Set citizen ID
     * @param id Citizen ID
    public void setId(Integer 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;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN" "">
<mapper namespace="cn.example.demo.mapper.CitizenDAO">

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

DAO interface

/* */
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