全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

代码生成器定制

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>

生成的代码结构对比

生成方式EntityMapper 接口Mapper XMLExample 类
MyBatis3完整 getter/setter完整 CRUD + Example 方法完整 SQL + Example SQL生成
MyBatis3Simple完整 getter/setter基础 CRUD基础 SQL不生成
自定义插件 + SimpleLombok 注解@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

注意事项

  1. 覆盖生成风险:设置 overwrite=true 时会直接覆盖已有文件,自定义修改的代码会丢失
  2. 插件执行顺序:多个插件按配置顺序依次执行,注意依赖关系
  3. 数据库注释读取:MySQL 需在 JDBC URL 中添加 useInformationSchema=true 才能读取字段注释
  4. 自定义插件调试:可在 validate() 方法中打印 warnings 辅助排查问题
  5. 多表批量生成:可使用 <table tableName="%"> 匹配所有表,但需注意表名前缀处理

要点总结

  • MBG 通过 generatorConfig.xml 配置数据源、包路径、表映射等基础规则
  • 通过继承 PluginAdapter 可自定义实体类注解、Mapper 接口修饰等生成逻辑
  • Lombok 插件可自动为实体类添加 @Data 等注解,简化代码
  • 自定义注释生成器可统一代码规范,添加作者、日期、表注释等信息
  • MyBatis3Simple 仅生成基础 CRUD,避免 Example 类冗余
  • 覆盖生成需谨慎,建议生成前备份自定义修改的代码

存放路径:D:\git2\jwdev\articles\MYBATIS\专家\生态工具与扩展\代码生成器定制.md

📝 发现内容有误?点击此处直接编辑

← 上一篇 PageHelper 分页插件
下一篇 → 生态工具对比
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库