Using MyBatis Generator for Code Generation and Practical CRUD Examples

This article explains how to set up the MyBatis Generator plugin in a Maven project, configure generatorConfig.xml and jdbc.properties, and demonstrates practical CRUD operations such as deleting users, updating team information, and performing fuzzy and range queries with generated Example classes.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Using MyBatis Generator for Code Generation and Practical CRUD Examples

The article provides a step‑by‑step guide for integrating MyBatis Generator into a Java backend project, including Maven plugin configuration, XML generator settings, JDBC properties, and practical usage examples.

1. Set up MyBatis Generator plugin environment

a. Add plugin dependency in pom.xml

<!--mybatis 逆向生成插件-->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <configuration>
        <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
</plugin>

b. Configure generatorConfig.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>
    <properties resource="jdbc.properties"/>
    <classPathEntry location="${jdbc_driverLocation}"/> <!-- specify JDBC driver jar -->
    
    <context id="default" targetRuntime="MyBatis3">
        <!-- comment generator settings -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        
        <!-- JDBC connection -->
        <jdbcConnection driverClass="${jdbc_driverClass}" 
                         connectionURL="${jdbc_url}" 
                         userId="${jdbc_user}" 
                         password="${jdbc_pwd}"/>
        
        <!-- Java model generator -->
        <javaModelGenerator targetPackage="com.rambo.sdm.dao.pojo" 
                               targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="constructorBased" value="true"/>
            <property name="trimStrings" value="true"/>
            <property name="immutable" value="false"/>
        </javaModelGenerator>
        
        <!-- SQL map generator -->
        <sqlMapGenerator targetPackage="com.rambo.sdm.dao.mapper" 
                           targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        
        <!-- Java client generator (XML mapper) -->
        <javaClientGenerator targetPackage="com.rambo.sdm.dao.inter" 
                               targetProject="src/main/java" 
                               type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        
        <!-- Table configuration example -->
        <table tableName="user" domainObjectName="UserPO">
            <generatedKey column="uuid" sqlStatement="SELECT REPLACE(UUID(),'-','') UUID FROM DUAL"/>
        </table>
    </context>
</generatorConfiguration>

c. Database configuration file jdbc.properties

jdbc_driverLocation=D:\Program Files\Repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar
jdbc_driverClass=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8
jdbc_user=root
jdbc_pwd=123456
validationQuery = select 1

d. Plugin execution configuration (image omitted)

2. Practical project examples

The following code snippets illustrate how to use the generated MyBatis artifacts for common operations such as deleting a user, updating team information, and performing various queries.

a. Delete a specific user's information under a team

public int deleteUserApplyInfo(long user_id, long team_id){
    StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();
    ue.createCriteria().andUserIdEqualTo(new BigDecimal(user_id))
                      .andTeamIdEqualTo(new BigDecimal(team_id));
    return studyTeamUserApplyInfoDAO.deleteByExample(ue);
}

b. Update team information based on non‑primary‑key team ID

public int updateStudyTeamInfo(StudyTeamInfo st){
    StudyTeamInfoExample ste = new StudyTeamInfoExample();
    ste.createCriteria().andTeamIdEqualTo(st.getTeamId());
    return studyTeamInfoDAO.updateByExampleSelective(st, ste);
}

c. Various queries

(1) Fuzzy search with sorting

public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){
    StudyTeamInfoExample se = new StudyTeamInfoExample();
    se.createCriteria().andTeamNameLike("%"+team_name+"%")
                      .andEnableEqualTo((short)1);
    se.setOrderByClause("team_score desc");
    List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);
    if(ls != null && ls.size() > 0){
        return ls;
    }
    return null;
}

(2) Query for scores within a range

public StudyTeamLevel getStudyTeamLevel(long score){
    StudyTeamLevelExample le = new StudyTeamLevelExample();
    le.createCriteria().andNeedScoreLessThanOrEqualTo(score)
                        .andUpScoreGreaterThan(score);
    List<StudyTeamLevel> ls = studyTeamLevelDAO.selectByExample(le);
    if(ls != null && ls.size() > 0){
        return ls.get(0);
    }
    return null;
}

By following these configurations and examples, developers can quickly generate MyBatis model, mapper, and XML files, and perform typical CRUD and query operations without writing repetitive boilerplate code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCode GenerationBackend DevelopmentMyBatisORM
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.