Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

MyBatis Generator: Code Generation for MyBatis Applications

Tech 1

Introduction to MyBatis Generator

MyBatis Generator (MBG), also referred to as MyBatis reverse engineering, is a specialized code generator designed for MyBatis framework users. It can rapidly generate corresponding mapping files, interfaces, and bean classes based on database tables. While it supports generating basic CRUD operations and QBC-style conditional queries, complex SQL definitions such as table joins and stored procedures need to be manually written.

This project is available on the MyBatis GitHub page (https://github.com/mybatis/generator).

Official documentation: http://www.mybatis.org/generator/
Official project: https://github.com/mybatis/generator/releases

Implementation Guide

1. Add Dependencies

To use MyBatis Generator, you need to include the database driver and mybatis-generator-core. If you want to test the generated code, also add mybatis.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example.mybatisdemo</groupId>
    <artifactId>mybatis-demo-mbg</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    
    <name>mybatis-demo-mbg</name>
    
    <packaging>jar</packaging>
    
    <description>MyBatis code generation example</description>
    
    <dependencies>
        <!-- MyBatis -->	
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        
        <!-- Database Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency>
        
        <!-- MyBatis Generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <!-- Log4j for logging -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>  
          <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <configuration>  
              <source>1.8</source>  
              <target>1.8</target>  
            </configuration>  
          </plugin>  
        </plugins>
    </build>
    
</project>

2. Create MBG Configuration File

Create a configuration file for MBG (the name is arbitrary) and place it in the classpath. Key configurations include:

  • <jdbcConnection>: Database connection information
  • <javaModelGenerator>: JavaBean generation strategy
  • <sqlMapGenerator>: SQL mapping file generation strategy
  • <javaClientGenerator>: Mapper interface generation strategy
  • <table>: Configuration for tables to generate code for

For more configuration options, refer to the official documentation under XML Configuration.

<?xml version="1.0" encoding="UTF-8"?>

<generatorConfiguration>
    
    <!-- 
        targetRuntime="MyBatis3Simple": Generates simple CRUD operations
        targetRuntime="MyBatis3": Generates enhanced CRUD with condition building and QBC support
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- jdbcConnection: Database connection settings -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true"
            userId="root"
            password="root">
        </jdbcConnection>

        <!-- Configuration for decimal handling -->
        <javaTypeResolver>
          <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 
            javaModelGenerator: JavaBean generation strategy 
            targetPackage="test.model": Target package name
            targetProject="\MBGTestProject\src": Target project
        -->
        <javaModelGenerator targetPackage="com.example.mybatis.entity" target=".\src\main\java">
                
          <property name="enableSubPackages" value="true" />
          <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- sqlMapGenerator: SQL mapping file generation strategy -->
        <sqlMapGenerator targetPackage="mybatis.mapper"  target=".\src\main\resources">
          <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- javaClientGenerator: Mapper interface generation strategy -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mybatis.mapper"  target=".\src\main\java">
            
          <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- Tables to generate code for -->
        <table tableName="employee" domainObjectName="Employee"></table>
    </context>
</generatorConfiguration>

3. Generate Code

Create and run a Java class to generate the code:

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

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;

public class CodeGenerator {
    
    public static void main(String[] args) throws Exception {
        generateMyBatisCode();
    }

    private static void generateMyBatisCode() throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        
        // Update this path to your configuration file location
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator generator = new MyBatisGenerator(config, callback, warnings);
        generator.generate(null);
    } 
}

Important Notes

  • The targetRuntime="MyBatis3" in the Context tag generates CRUD operations with conditions, including condition-building code and QBC support.
  • The targetRuntime="MyBatis3Simple" generates basic CRUD operations only.
  • If regenerating code, it's recommended to delete previously generated data to avoid issues with XML content being appended.
  • To use Hibernate-like QBC queries, generate code with targetRuntime="MyBatis3". This creates code with condition-building SQL and additional xxxExample classes for complex query conditions.

Example Using QBC Queries

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.example.mybatis.entity.Employee;
import com.example.mybatis.entity.EmployeeExample;
import com.example.mybatis.entity.EmployeeExample.Criteria;
import com.example.mybatis.mapper.EmployeeMapper;

public class QueryExample {
    
    public static void main(String[] args) throws Exception {
        testQBCquery();
    }    
    /**
     * To use Hibernate-like QBC queries, generate code with targetRuntime="MyBatis3"
     * This creates code with condition-building SQL and additional xxxExample classes for complex query conditions
     * 
     * @throws Exception
     */
    public static void testQBCquery() throws Exception{
        // 1. Create SqlSessionFactory from XML configuration file
        String resource = "mybatis/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        // 2. Get SqlSession to execute mapper XML files
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            // 3. Get mapper interface implementation object
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
            
            // Test 1: Query all (simple query)
            // List<Employee> emps = mapper.selectByExample(null);
            
            // Test 2: Query employees with 'e' in name and gender = '1'
            // Create EmployeeExample for query conditions
            EmployeeExample example = new EmployeeExample();
            
            // Create Criteria to build query conditions
            // SELECT id, last_name, email, gender, d_id FROM employee WHERE (last_name LIKE ? AND gender = ?) OR email LIKE "%e%"
            Criteria criteria = example.createCriteria();
            criteria.andLastNameLike("%e%");
            criteria.andGenderEqualTo("1");
            
            Criteria criteria2 = example.createCriteria();
            criteria2.andEmailLike("%e%");
            example.or(criteria2);
            
            List<Employee> employees = mapper.selectByExample(example);
            for (Employee employee : employees) {
                System.out.println(employee.getId());
            }
            
        }finally{
            sqlSession.close();
        }
    }
}

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.