逆向工程
MyBatis 逆向工程全指南:从配置到高级定制(含 IDEA 实战与避坑)
MyBatis 逆向工程(MyBatis Generator,简称 MBG)是 MyBatis 官方提供的代码生成工具,可根据数据库表自动生成 实体类、Mapper 接口、Mapper XML 文件,大幅减少重复的 CRUD 代码编写工作。 依赖优化、高级配置(如分页 / 注释 / 逻辑删除)、IDEA 快捷配置、常见问题解决方案 及 工程化最佳实践,帮助你高效落地逆向工程。
逆向工程核心依赖与版本选型
1. Maven 依赖配置
<dependencies>
<!-- MyBatis 核心依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<!-- MyBatis 逆向工程核心包 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.2</version> <!-- 最新稳定版,修复旧版bug -->
<scope>provided</scope> <!-- 仅编译期使用,避免打包到生产环境 -->
</dependency>
<!-- MySQL 驱动(需与数据库版本匹配,8.0+用8.x版本) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
<!-- 日志依赖(便于查看逆向工程执行日志,可选) -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 可选:配置 Maven 插件,通过命令行执行逆向工程 -->
<build>
<plugins>
<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>
<!-- 执行后是否覆盖已有文件(建议开发期设为true) -->
<overwrite>true</overwrite>
<!-- 打印执行日志 -->
<verbose>true</verbose>
</configuration>
<dependencies>
<!-- 插件依赖的数据库驱动(避免版本冲突) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>