# SpringBoot整合Mybatis Generator自動生成的示例分析
## 1. MyBatis Generator簡介
### 1.1 核心功能概述
MyBatis Generator(簡稱MBG)是MyBatis官方提供的代碼生成工具,能夠根據數據庫表結構自動生成以下內容:
- 實體類(POJO)
- Mapper接口
- XML映射文件
- 動態查詢條件類(Example類)
### 1.2 典型應用場景
1. **快速開發**:減少70%以上的重復CRUD代碼編寫
2. **規范統一**:保證項目中的持久層代碼風格一致
3. **維護便捷**:表結構變更后重新生成即可同步更新
## 2. 環境準備
### 2.1 基礎環境要求
| 組件 | 版本要求 |
|--------------|---------------|
| JDK | 1.8+ |
| Spring Boot | 2.3.x+ |
| MyBatis | 3.5.0+ |
| MySQL | 5.7+ |
### 2.2 Maven依賴配置
```xml
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis整合Spring Boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- MyBatis Generator核心 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
application.yml
示例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mbg_demo?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.mbg.model
pom.xml
中添加構建插件:
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
generatorConfig.xml
完整配置:
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-configuration_1_0.dtd">
<generatorConfiguration>
<!-- 數據庫驅動路徑 -->
<classPathEntry location="/path/to/mysql-connector-java-8.0.25.jar"/>
<context id="mysqlTables" targetRuntime="MyBatis3">
<!-- 生成的Java文件編碼 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 自動生成注釋配置 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="false"/>
</commentGenerator>
<!-- 數據庫連接配置 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mbg_demo"
userId="root"
password="123456">
</jdbcConnection>
<!-- Java模型生成配置 -->
<javaModelGenerator
targetPackage="com.example.mbg.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.mbg.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 表配置 -->
<table tableName="user_info" domainObjectName="User">
<generatedKey column="id" sqlStatement="MySQL" identity="true"/>
</table>
<table tableName="product">
<columnOverride column="price" javaType="java.math.BigDecimal"/>
</table>
</context>
</generatorConfiguration>
targetRuntime:
table元素屬性:
<table
tableName="%" <!-- 匹配所有表 -->
enableCountByExample="false" <!-- 禁用計數查詢 -->
enableUpdateByExample="false"
enableDeleteByExample="false"
selectByExampleQueryId="false">
列級自定義:
<table tableName="employee">
<columnOverride column="hire_date" property="hireDate"
javaType="java.time.LocalDate"/>
<ignoreColumn column="deleted"/>
</table>
mvn mybatis-generator:generate
src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── mbg/
│ │ ├── model/ # 實體類
│ │ └── mapper/ # Mapper接口
│ └── resources/
│ └── mapper/ # XML映射文件
public class User {
private Long id;
private String username;
private Integer age;
private Date createTime;
// getters/setters省略
}
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
User selectByPrimaryKey(Long id);
List<User> selectAll();
int updateByPrimaryKey(User record);
// 動態條件查詢
List<User> selectByExample(UserExample example);
int updateByExampleSelective(@Param("record") User record,
@Param("example") UserExample example);
}
<resultMap id="BaseResultMap" type="User">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" suffix=")" prefixOverrides="and">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
實現PluginAdapter
擴展生成邏輯:
public class LombokPlugin extends PluginAdapter {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 添加Lombok注解
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addAnnotation("@Data");
return true;
}
}
配置使用插件:
<context id="mysqlTables" targetRuntime="MyBatis3">
<plugin type="com.example.plugin.LombokPlugin"/>
</context>
// 創建條件對象
UserExample example = new UserExample();
example.createCriteria()
.andUsernameLike("%admin%")
.andAgeBetween(20, 30)
.andCreateTimeGreaterThan(new Date());
// 排序設置
example.setOrderByClause("create_time DESC");
// 執行查詢
List<User> users = userMapper.selectByExample(example);
結合PageHelper實現分頁:
@GetMapping("/users")
public PageInfo<User> getUsers(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
PageHelper.startPage(pageNum, pageSize);
UserExample example = new UserExample();
example.setOrderByClause("id DESC");
List<User> users = userMapper.selectByExample(example);
return new PageInfo<>(users);
}
檢查數據庫連接:
表名大小寫問題:
<table tableName="USER_INFO" delimitIdentifiers="true"/>
日志分析:
<context id="mysqlTables">
<property name="logImpl" value="SLF4J"/>
</context>
自定義類型轉換器:
<table tableName="product">
<columnOverride column="status"
javaType="com.example.enums.ProductStatus"
typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
</table>
部分覆蓋策略:
<context id="mysqlTables">
<property name="mergeable" value="true"/>
</context>
自定義生成策略:
public class CustomGenerator extends DefaultShellCallback {
@Override
public boolean isMergeSupported() {
return true;
}
}
啟用二級緩存
<cache eviction="LRU" flushInterval="60000"/>
批量操作示例
@Insert("<script>insert into user (username) values " +
"<foreach collection='list' item='item' separator=','>(#{item.username})</foreach></script>")
void batchInsert(List<User> users);
版本控制策略:
項目目錄規范:
src/
├── generated/ # 生成的代碼
├── main/ # 手動編寫的代碼
└── resources/
├── generator/ # MBG配置文件
└── mapper/ # 自定義SQL片段
持續集成集成:
<plugin>
<executions>
<execution>
<id>generate-mybatis</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
通過本文的詳細講解,我們系統性地掌握了Spring Boot與MyBatis Generator的整合方法。合理使用代碼生成工具可以顯著提升開發效率,但同時需要注意: 1. 生成的代碼需要二次審查 2. 復雜查詢仍需手動編寫SQL 3. 及時更新生成配置保持與數據庫同步
建議在實際項目中結合具體需求靈活運用本文介紹的技術方案,打造高效穩定的數據訪問層。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。