Automate MyBatis Code Generation in Spring Boot with MyBatis Generator
This guide shows how to integrate the MyBatis Generator Maven plugin into a Spring Boot project, configure generatorConfig.xml, run the plugin to auto‑create entity, mapper, and XML files from database tables, and use the generated code in a service layer.
Plugin Integration
After completing the Spring Boot and MyBatis integration, you can add the mybatis-generator-maven-plugin to the pom.xml build plugins. The plugin requires the MySQL driver as a dependency.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- MyBatis Generator 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/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>Reverse Generation Configuration
Create generatorConfig.xml under src/main/resources/generator (or any location you prefer). The file defines the database connection, target packages for generated POJOs, mapper XML, and mapper interfaces, and specifies which tables to generate.
<?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="MySql" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- Database connection -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/spring"
userId="root"
password="root" />
<!-- POJO output location -->
<javaModelGenerator targetPackage="com.secbro.model" targetProject="src/main/java" />
<!-- Mapper XML output location -->
<sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources" />
<!-- Mapper interface output location -->
<javaClientGenerator targetPackage="com.secbro.mapper" targetProject="src/main/java" type="XMLMAPPER" />
<!-- Table to generate -->
<table tableName="tb_order" domainObjectName="Order">
<generatedKey column="id" sqlStatement="MySql" identity="true" />
</table>
</context>
</generatorConfiguration>Running the Generator
Open the Maven tool window in IntelliJ IDEA, locate the mybatis-generator:generate goal under the Plugins section, and double‑click it. The plugin connects to the database, reads the table metadata, and creates the corresponding Java classes and XML files in the directories defined above.
Generated Files
Order entity class
package com.secbro.model;
import java.io.Serializable;
public class Order implements Serializable {
private Integer id;
private String orderNo;
// ... other fields and methods
}OrderExample class (criteria builder)
package com.secbro.model;
import java.util.ArrayList;
import java.util.List;
public class OrderExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public OrderExample() {
oredCriteria = new ArrayList<>();
}
// getters, setters, and inner Criteria classes omitted for brevity
}OrderMapper interface
package com.secbro.mapper;
import com.secbro.model.Order;
import com.secbro.model.OrderExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface OrderMapper {
long countByExample(OrderExample example);
int deleteByExample(OrderExample example);
int deleteByPrimaryKey(Integer id);
int insert(Order record);
int insertSelective(Order record);
List<Order> selectByExample(OrderExample example);
Order selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Order record, @Param("example") OrderExample example);
int updateByExample(@Param("record") Order record, @Param("example") OrderExample example);
int updateByPrimaryKeySelective(Order record);
int updateByPrimaryKey(Order record);
}OrderMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.secbro.mapper.OrderMapper">
<resultMap id="BaseResultMap" type="com.secbro.model.Order">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="order_no" jdbcType="VARCHAR" property="orderNo" />
<result column="amount" jdbcType="INTEGER" property="amount" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">and ${criterion.condition}</when>
<when test="criterion.singleValue">and ${criterion.condition} #{criterion.value}</when>
<when test="criterion.betweenValue">and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}</when>
<when test="criterion.listValue">and ${criterion.condition} (
<foreach collection="criterion.value" item="listItem" open="(" separator="," close=")">#{listItem}</foreach>
)</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<!-- Additional CRUD statements omitted for brevity -->
</mapper>Usage Example
With @MapperScan("com.secbro.mapper") already configured, you can inject OrderMapper into a service and use it directly.
@Service("orderService")
public class OrderServiceImpl implements OrderService {
@Resource
private OrderMapper orderMapper;
@Override
public Order findByOrderNo(String orderNo) {
OrderExample example = new OrderExample();
example.createCriteria().andOrderNoEqualTo(orderNo);
List<Order> list = orderMapper.selectByExample(example);
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
}Conclusion
By configuring the MyBatis Generator plugin and providing a proper generatorConfig.xml, you can automatically generate POJOs, mapper interfaces, and XML files from existing database tables, dramatically reducing boilerplate code and letting you focus on core business logic. The plugin also supports customization of generated code through its configuration options.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
