Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating MyBatis Generator with a Custom Mapper Plugin

Tech Sep 12 1

Configuring MBG with Maven

An example from the Mybatis-Spring project demonstrates this integration.

Using the Maven plugin allows referencing Maven properties in generatorConfig.xml via the ${property} syntax.

First, examine the relevant section of the pom.xml configuraton:

<properties>
    <!-- MyBatis Generator Settings -->
    <javaSourceDir>${basedir}/src/main/java</javaSourceDir>
    <mapperInterfacePackage>com.example.dao</mapperInterfacePackage>
    <entityPackage>com.example.entity</entityPackage>
    <!-- Resource Directory for XML -->
    <resourceDir>${basedir}/src/main/resources</resourceDir>
    <xmlMapperDir>mappers</xmlMapperDir>
    <!-- Dependency Versions -->
    <custom.mapper.version>2.0.1</custom.mapper.version>
    <db.driver.version>8.0.33</db.driver.version>
</properties>

The properties section defines paths, package names, and dependency versions used in the MBG configuration.

Next, configrue the MBG Maven plugin:

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.4.0</version>
    <configuration>
        <configurationFile>${basedir}/src/main/resources/generator-config.xml</configurationFile>
        <overwrite>true</overwrite>
        <verbose>true</verbose>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${db.driver.version}</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>custom-mapper</artifactId>
            <version>${custom.mapper.version}</version>
        </dependency>
    </dependencies>
</plugin>

This setup specifies the MBG configuration file location and includes necessary dependencies: the JDBC driver and the custom Mapper library (which provides the MBG plugin).

Now, review the generator-config.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<generatorConfiguration>
    <properties resource="application.properties"/>

    <context id="MySQLTarget" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="${generator.plugin.class}">
          <property name="baseMapperInterface" value="${mapper.base.interface}"/>
        </plugin>

        <jdbcConnection driverClass="${database.driver}"
                        connectionURL="${database.url}"
                        userId="${database.username}"
                        password="${database.password}">
        </jdbcConnection>

        <javaModelGenerator targetPackage="${entityPackage}" targetProject="${javaSourceDir}"/>

        <sqlMapGenerator targetPackage="${xmlMapperDir}" targetProject="${resourceDir}"/>

        <javaClientGenerator targetPackage="${mapperInterfacePackage}" targetProject="${javaSourceDir}" type="XMLMAPPER" />

        <generatedkey column="id" identity="true" sqlstatement="MySQL"></generatedkey>
    </context>
</generatorConfiguration>

Most properties in this configuration use placeholders. The directive <properties resource="application.properties"/> imports properties from application.properties:

# Database Configuration
database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/app_db
database.username=app_user
database.password=secret

# Connection Pool Settings
connection.pool.maxSize=30
connection.pool.minSize=5

# MyBatis Generator Plugin Configuration
generator.plugin.class=com.example.generator.CustomMapperPlugin
mapper.base.interface=com.example.mapper.BaseMapper

Using a property file centralizes configuration used across the application.

Some placeholders reference values from the pom.xml file, offering greater flexibility.

Execution

To run the generator, execute the following command in the terminal from the directory containing the pom.xml file: mvn mybatis-generator:generate (assuming Maven is configured).

Generated Artifacts

Examples of the generated code follow.

Entity Class Account

package com.example.entity;

import javax.persistence.*;

@Table(name = "account")
public class Account {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * User login name
     */
    private String loginName;

    /**
     * Encrypted password hash
     */
    private String passHash;

    /**
     * @return id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * Get user login name
     *
     * @return loginName - User login name
     */
    public String getLoginName() {
        return loginName;
    }

    /**
     * Set user login name
     *
     * @param loginName User login name
     */
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
}

The ganerated comments are derived from the database column remarks. Annotations are also automatically included.

Mapper Interface AccountMapper

package com.example.dao;

import com.example.mapper.BaseMapper;
import com.example.entity.Account;

public interface AccountMapper extends BaseMapper<Account> {
}

The interface automatically extends the configured base Mapper interface with the correct entity type.

XML Mapping File AccountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="com.example.dao.AccountMapper">
    <resultMap id="BaseResultMap" type="com.example.entity.Account">
        <!--
            WARNING - @mbggenerated
        -->
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="login_name" property="loginName" jdbcType="VARCHAR" />
        <result column="pass_hash" property="passHash" jdbcType="VARCHAR" />
        <result column="created_at" property="createdAt" jdbcType="TIMESTAMP" />
        <result column="is_active" property="isActive" jdbcType="BOOLEAN" />
    </resultMap>
</mapper>

The XML file contains the entity's resultMap definition.

In Eclipse/IDE, right-click the pom.xml file, select Run As → Maven Build..., and enter mybatis-generator:generate in the Goals field.

From the command line, ensure you are in the project root directory and run: mvn mybatis-generator:generate.

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.