How to Use MyBatis Generator to Generate Database Access Code in the Mall Project
The macrozheng/mall repository provides a pre-configured MyBatis Generator (MBG) setup that automatically creates model classes, mapper interfaces, and XML mappings from your MySQL schema using a single Maven command.
The macrozheng/mall project streamlines database access layer development by integrating MyBatis Generator directly into its Maven build lifecycle. This configuration eliminates boilerplate code by automatically generating POJOs, SQL mappers, and Java client interfaces from existing database tables. Developers can regenerate the entire data-access layer whenever the schema changes, ensuring Java code remains synchronized with the underlying MySQL structure.
MyBatis Generator Configuration Architecture
The generatorConfig.xml File
The central configuration resides in mall-mbg/src/main/resources/generatorConfig.xml. This file defines a single context named MySqlContext with targetRuntime="MyBatis3" and defaultModelType="flat", which generates separate POJO and Example classes for complex queries.
The configuration uses property placeholders to externalize credentials:
<property name="jdbc.url" value="${jdbc.url}"/>
<property name="jdbc.username" value="${jdbc.username}"/>
<property name="jdbc.password" value="${jdbc.password}"/>
This approach references values from your environment (typically application-dev.yml), keeping sensitive information out of version control.
The file specifies three critical generators:
- Java Model Generator: Targets
com.macro.mall.tiny.mbg.modelfor POJO classes - SQL Map Generator: Places XML files in the
mapperpackage undermall-mbg/src/main/resources - Java Client Generator: Creates mapper interfaces in
com.macro.mall.tiny.mbg.mapperusingtype="XMLMAPPER"
Maven Plugin Integration
Plugin Declaration in pom.xml
The root pom.xml binds the mybatis-generator-maven-plugin (version 1.4.0) to the generate-sources phase:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<configurationFile>mall-mbg/src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
</plugin>
The configurationFile element points to the XML configuration, while overwrite set to true allows iterative regeneration without manual file deletion. The verbose flag enables detailed logging during the generation process.
Running the Generator
Execute the following command from the repository root to generate the database access layer:
mvn mybatis-generator:generate
During execution, MBG connects to the MySQL database using the JDBC properties from your environment, introspects the schema, and writes artifacts to:
- Model classes:
mall-mbg/src/main/java/com/macro/mall/tiny/mbg/model/(e.g.,PmsProduct.java) - Mapper interfaces:
mall-mbg/src/main/java/com/macro/mall/tiny/mbg/mapper/(e.g.,PmsProductMapper.java) - XML mappings:
mall-mbg/src/main/resources/mapper/(e.g.,PmsProductMapper.xml)
Working with Generated Artifacts
Spring Boot Auto-Configuration
The generated mapper interfaces include the @Mapper annotation, enabling automatic discovery by mybatis-spring-boot-starter. The project's pom.xml includes this starter dependency, allowing Spring to scan the com.macro.mall.tiny.mbg.mapper package without additional configuration.
Service Layer Integration
The generated code works seamlessly with the project's transaction management and pagination support. The pagehelper-spring-boot-starter (declared in pom.xml) enables pagination on generated methods:
@Service
public class ProductService {
@Autowired
private PmsProductMapper productMapper;
public List<PmsProduct> listProducts(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
PmsProductExample example = new PmsProductExample();
return productMapper.selectByExample(example);
}
}
Service layers can autowire these mappers and use them within @Transactional boundaries for automatic transaction participation.
Customizing Table Selection
Selective Generation
Instead of using the wildcard <table tableName="*"/> to generate code for all tables, you can add specific entries to generatorConfig.xml for targeted generation:
<table tableName="new_table" domainObjectName="NewEntity"/>
After modifying the configuration, re-run the Maven command. MBG will create NewEntity.java, NewEntityMapper.java, and NewEntityMapper.xml based on the specified table structure without affecting existing generated files for other tables.
Summary
- MyBatis Generator in the Mall project is configured via
mall-mbg/src/main/resources/generatorConfig.xmlusing environment variables for database credentials - The Maven plugin in the root
pom.xmlenables execution viamvn mybatis-generator:generatewithoverwriteenabled for iterative regeneration - Generated artifacts include flat-model POJOs in
com.macro.mall.tiny.mbg.model, XMLMAPPER interfaces incom.macro.mall.tiny.mbg.mapper, and SQL XML files inresources/mapper - The generated code integrates automatically with Spring Boot through the
mybatis-spring-boot-starterand supports pagination viapagehelper-spring-boot-starter - Developers can target specific tables by adding
<table>elements with explicittableNameanddomainObjectNameattributes
Frequently Asked Questions
Where is the MyBatis Generator configuration located in the Mall project?
The configuration file is located at mall-mbg/src/main/resources/generatorConfig.xml. This XML file defines the database connection properties using placeholders like ${jdbc.url}, target packages for generated code, and table mappings. It references environment variables to keep credentials secure and out of source control.
How do I regenerate code after changing the database schema?
Run mvn mybatis-generator:generate from the repository root. The Maven plugin is configured with <overwrite>true</overwrite>, which automatically replaces existing generated files with updated versions reflecting the current database structure. Ensure your JDBC properties are correctly configured in application-dev.yml or your active profile before executing the command.
Can I generate code for only specific tables instead of the entire database?
Yes. In generatorConfig.xml, replace the wildcard <table tableName="*"/> with specific entries like <table tableName="pms_product" domainObjectName="Product"/>. Each <table> element can specify custom domain object names and column overrides. After modifying the configuration, execute the Maven generate command to produce code only for the specified tables.
How does the generated code integrate with Spring Boot in the Mall project?
The generated mapper interfaces include the @Mapper annotation, which allows mybatis-spring-boot-starter to automatically scan and register them as Spring beans during component scanning. The project also includes pagehelper-spring-boot-starter, enabling methods like selectByExample to support pagination through PageHelper.startPage() calls without additional mapper configuration.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →