在使用 MyBatis 或 MyBatis Plus 等框架开发时,可以通过配置 Maven 插件来自动生成实体类、Mapper 接口及对应的 XML 映射文件。以下是使用 MyBatis Generator 和 Maven 插件进行自动代码生成的基本步骤:
1. 添加 MyBatis Generator Maven Plugin 在项目的 pom.xml 文件中添加 MyBatis Generator 的 Maven 插件配置。确保你已经安装了 Java 和 Maven,并且项目结构支持 Maven。
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<!-- 这里添加你的数据库驱动依赖 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2. 创建 generatorConfig.xml 配置文件
在 src/main/resources 目录下创建 generatorConfig.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="D:/Program Files/m2/repository"/>
<context id="dbTables" targetRuntime="MyBatis3Simple">
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"
userId="root"
password="password">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<javaModelGenerator targetPackage="com.example.model" targetProject="D:/workspace">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.example.mapper" targetProject="D:/workspace/src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="D:/workspace/src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="your_table_name" domainObjectName="YourEntityName" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
3. 执行生成
保存配置后,可以在命令行中进入项目根目录,然后运行如下命令来触发代码生成:
mvn mybatis-generator:generate
这个命令会根据 generatorConfig.xml 文件中的配置生成相应的实体类、Mapper 接口和 XML 映射文件。
4. 集成到项目构建周期
如果希望每次构建项目时都自动执行代码生成,可以在 <build> 标签下的 <plugins> 中为 MyBatis Generator 插件添加 executions 标签,将其绑定到 Maven 的生命周期阶段,如 compile 或 process-resources。