您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot如何集成MyBatis官方生成器
## 一、前言
在现代Java企业级应用开发中,SpringBoot和MyBatis的组合因其高效、灵活的特性被广泛采用。MyBatis官方提供的代码生成器(MyBatis Generator,简称MBG)能够自动生成实体类、Mapper接口和XML映射文件,显著提升开发效率。本文将详细介绍如何在SpringBoot项目中集成MyBatis官方生成器。
## 二、环境准备
### 1. 基础环境要求
- JDK 1.8+
- Maven 3.6+ 或 Gradle 6.x+
- SpringBoot 2.5+(本文以2.7.0为例)
- MyBatis 3.5+
### 2. 创建SpringBoot项目
使用Spring Initializr创建项目时需勾选:
- Spring Web
- MyBatis Framework
- MySQL Driver(或其他数据库驱动)
或通过命令创建:
```bash
mvn archetype:generate -DgroupId=com.example -DartifactId=mybatis-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
在pom.xml中添加MBG插件和数据库驱动:
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
在src/main/resources下创建配置文件:
<?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="MySQLTables" targetRuntime="MyBatis3">
<!-- 生成的Java文件编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 注释配置 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接配置 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123456">
</jdbcConnection>
<!-- Java模型生成器 -->
<javaModelGenerator
targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- SQL映射文件生成器 -->
<sqlMapGenerator
targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mapper接口生成器 -->
<javaClientGenerator
type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 指定要生成的表 -->
<table tableName="user" domainObjectName="User"/>
</context>
</generatorConfiguration>
application.yml配置示例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// 配置XML文件位置
sessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml"));
return sessionFactory.getObject();
}
}
通过Maven命令执行生成:
mvn mybatis-generator:generate
或配置自动生成:
<plugin>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
生成成功后项目中将出现:
src/
├── main/
│ ├── java/
│ │ └── com/example/
│ │ ├── model/User.java
│ │ └── mapper/UserMapper.java
│ └── resources/
│ └── mapper/UserMapper.xml
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
}
<context id="MySQLTables" targetRuntime="MyBatis3">
<javaTypeResolver>
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>
</context>
<table tableName="user" domainObjectName="User"
enableCountByExample="true"
enableUpdateByExample="true"
enableDeleteByExample="true"
enableSelectByExample="true"
selectByExampleQueryId="true"/>
实现Plugin接口:
public class CustomPlugin extends PluginAdapter {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 添加自定义注解
topLevelClass.addAnnotation("@lombok.Data");
return true;
}
}
添加Lombok依赖后,在generatorConfig.xml中配置:
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
对于Maven多模块项目,需指定正确的targetProject路径:
<javaModelGenerator
targetPackage="com.example.model"
targetProject="${project.basedir}/core/src/main/java">