代码生成器定制
MyBatis Generator(MBG)是官方提供的代码生成工具,可根据数据库表结构自动生成 Entity、Mapper 接口与 XML 文件。但在实际项目中,默认生成的代码往往不符合团队的编码规范,需要通过插件和自定义模板进行深度定制。
MBG 基础使用
依赖引入
XML
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.2</version>
</dependency>
<!-- Maven 插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.2</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
</plugin>
generatorConfig.xml 基础配置
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>
<!-- 数据库驱动 -->
<classPathEntry location="/path/to/mysql-connector-java.jar"/>
<context id="MySQL" targetRuntime="MyBatis3">
<!-- 数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mydb"
userId="root"
password="123456"/>
<!-- 实体类生成 -->
<javaModelGenerator targetPackage="com.example.entity"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- Mapper XML 生成 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- Mapper 接口生成 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 表映射 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
注意:
targetRuntime="MyBatis3"会生成大量 Example 类,若不需要可设为MyBatis3Simple。
自定义插件开发
MBG 提供了插件扩展机制,通过继承 PluginAdapter 可在代码生成过程中注入自定义逻辑。
插件接口
Java
public class CustomPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
// 插件校验逻辑,返回 false 则中断生成
return true;
}
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 在实体类生成时介入
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 在 Mapper 接口生成时介入
return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
}
}
实战:为实体类添加 Lombok 注解
Java
public class LombokPlugin extends PluginAdapter {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 添加 @Data 注解
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addAnnotation("@Data");
// 添加 @NoArgsConstructor
topLevelClass.addImportedType("lombok.NoArgsConstructor");
topLevelClass.addAnnotation("@NoArgsConstructor");
// 添加 @AllArgsConstructor
topLevelClass.addImportedType("lombok.AllArgsConstructor");
topLevelClass.addAnnotation("@AllArgsConstructor");
return true;
}
@Override
public boolean validate(List<String> warnings) {
return true;
}
}
实战:为 Mapper 接口添加 @Repository 注解
Java
public class RepositoryAnnotationPlugin extends PluginAdapter {
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 添加 @Repository 注解
interfaze.addImportedType("org.springframework.stereotype.Repository");
interfaze.addAnnotation("@Repository");
return true;
}
@Override
public boolean validate(List<String> warnings) {
return true;
}
}
配置自定义插件
XML
<context id="MySQL" targetRuntime="MyBatis3Simple">
<!-- 注册自定义插件 -->
<plugin type="com.example.generator.LombokPlugin"/>
<plugin type="com.example.generator.RepositoryAnnotationPlugin"/>
<!-- 其他配置 ... -->
</context>
自定义注释生成器
默认 MBG 生成的注释包含生成时间等冗余信息,可通过自定义注释生成器统一格式。
Java
public class CustomCommentGenerator extends DefaultCommentGenerator {
@Override
public void addModelClassComment(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + introspectedTable.getRemarks() + " 实体类");
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author 小智");
topLevelClass.addJavaDocLine(" * @date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
topLevelClass.addJavaDocLine(" */");
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (StringUtils.isNotBlank(introspectedColumn.getRemarks())) {
field.addJavaDocLine("/** " + introspectedColumn.getRemarks() + " */");
}
}
}
配置自定义注释生成器:
XML
<context id="MySQL" targetRuntime="MyBatis3Simple">
<commentGenerator type="com.example.generator.CustomCommentGenerator">
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="false"/>
</commentGenerator>
<!-- 其他配置 ... -->
</context>
覆盖默认模板
禁用 Example 类生成
XML
<table tableName="user" domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
仅生成基础 CRUD
使用 targetRuntime="MyBatis3Simple":
XML
<context id="MySQL" targetRuntime="MyBatis3Simple">
<!-- 仅生成 selectByPrimaryKey, insert, updateByPrimaryKey, deleteByPrimaryKey -->
</context>
生成时忽略特定列
XML
<table tableName="user" domainObjectName="User">
<!-- 忽略 create_time 列,不生成对应属性 -->
<ignoreColumn column="create_time"/>
<!-- 重命名列:DB 字段为 user_name,实体属性改为 username -->
<columnOverride column="user_name" property="username"/>
</table>
生成的代码结构对比
| 生成方式 | Entity | Mapper 接口 | Mapper XML | Example 类 |
|---|---|---|---|---|
| MyBatis3 | 完整 getter/setter | 完整 CRUD + Example 方法 | 完整 SQL + Example SQL | 生成 |
| MyBatis3Simple | 完整 getter/setter | 基础 CRUD | 基础 SQL | 不生成 |
| 自定义插件 + Simple | Lombok 注解 | @Repository + 基础 CRUD | 基础 SQL | 不生成 |
集成 Maven 构建
XML
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.2</version>
<dependencies>
<!-- 自定义插件 JAR -->
<dependency>
<groupId>com.example</groupId>
<artifactId>mybatis-generator-plugins</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
执行生成:
Bash
mvn mybatis-generator:generate
注意事项
- 覆盖生成风险:设置
overwrite=true时会直接覆盖已有文件,自定义修改的代码会丢失- 插件执行顺序:多个插件按配置顺序依次执行,注意依赖关系
- 数据库注释读取:MySQL 需在 JDBC URL 中添加
useInformationSchema=true才能读取字段注释- 自定义插件调试:可在
validate()方法中打印 warnings 辅助排查问题- 多表批量生成:可使用
<table tableName="%">匹配所有表,但需注意表名前缀处理
要点总结
- MBG 通过
generatorConfig.xml配置数据源、包路径、表映射等基础规则 - 通过继承
PluginAdapter可自定义实体类注解、Mapper 接口修饰等生成逻辑 - Lombok 插件可自动为实体类添加
@Data等注解,简化代码 - 自定义注释生成器可统一代码规范,添加作者、日期、表注释等信息
MyBatis3Simple仅生成基础 CRUD,避免 Example 类冗余- 覆盖生成需谨慎,建议生成前备份自定义修改的代码
存放路径:D:\git2\jwdev\articles\MYBATIS\专家\生态工具与扩展\代码生成器定制.md
📝 发现内容有误?点击此处直接编辑