Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Automating MyBatis Mapping Code from Database Metadata

Tech 2

Add the MyBatis Generator core library along with your database driver to your project dependencies:

<dependencies>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.2</version>
    </dependency>
</dependencies>

Configure the generation behavior through an XML descriptor placed at src/main/resources/generatorConfiguration.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>
    <context id="productionContext" targetRuntime="MyBatis3DynamicSql">
        <property name="autoDelimitKeywords" value="true"/>
        
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://127.0.0.1:3306/corporate_db?useSSL=false&amp;serverTimezone=Asia/Tokyo"
            userId="dbadmin"
            password="securePass">
        </jdbcConnection>
        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>
        
        <javaModelGenerator targetPackage="com.example.domain.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        
        <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.persistence" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        
        <table tableName="department" domainObjectName="DepartmentInfo"
               enableCountByExample="true" enableUpdateByExample="true" 
               enableDeleteByExample="true" enableSelectByExample="true">
            <columnOverride column="dept_code" javaType="String" jdbcType="VARCHAR"/>
        </table>
    </context>
</generatorConfiguration>

Implement a bootstrap class to trigger the generation process programmatically:

package com.example.codegen;

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;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DatabaseSchemaProcessor {
    
    public void executeGeneration() throws Exception {
        List<String> notifications = new ArrayList<>();
        boolean allowOverride = true;
        
        File xmlConfig = new File(Thread.currentThread()
            .getContextClassLoader()
            .getResource("generatorConfiguration.xml")
            .toURI());
        
        ConfigurationParser configParser = new ConfigurationParser(notifications);
        Configuration generatorConfig = configParser.parseConfiguration(xmlConfig);
        DefaultShellCallback shellCallback = new DefaultShellCallback(allowOverride);
        
        MyBatisGenerator generator = new MyBatisGenerator(
            generatorConfig, shellCallback, notifications);
        generator.generate(null);
        
        notifications.forEach(System.out::println);
    }
    
    public static void main(String[] args) {
        try {
            new DatabaseSchemaProcessor().executeGeneration();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The tool generates entity classes in the specified model package, mapping interfaces in the persistence layer, and corresponding XML files containing SQL statements. These artifacts implement standard persistence operations including selective inserts, updates by primary key, and complex query capabilities through generated example classes. Adjust the targetProject attributes to align with your specific build layout, using filesystem paths relative to the configuration file location or absolute paths as needed.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.