# Spring Boot 2.0中怎么整合MyBatis 3
## 前言
在現代Java企業級應用開發中,Spring Boot憑借其"約定優于配置"的理念和快速開發能力已成為事實上的標準框架。而MyBatis作為一款優秀的持久層框架,因其靈活的SQL編寫方式和良好的性能表現廣受歡迎。本文將詳細介紹如何在Spring Boot 2.0項目中整合MyBatis 3,涵蓋從環境搭建到高級配置的全過程。
## 一、環境準備
### 1.1 創建Spring Boot項目
首先我們需要創建一個基礎的Spring Boot 2.0項目(實際版本建議使用2.0.x系列穩定版):
```xml
<!-- pom.xml 基礎依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Spring Boot官方提供了對MyBatis的starter支持:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version> <!-- 對應MyBatis 3.4.x版本 -->
</dependency>
<!-- 數據庫驅動,以MySQL為例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
在application.yml中配置數據源:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml # XML映射文件位置
type-aliases-package: com.example.model # 實體類包路徑
configuration:
map-underscore-to-camel-case: true # 開啟駝峰命名轉換
package com.example.model;
public class User {
private Long id;
private String username;
private String email;
// 省略getter/setter
}
@Mapper // 重要:必須添加此注解
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO users(username,email) VALUES(#{username},#{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
// 更多方法...
}
對于復雜SQL,推薦使用XML方式:
<!-- src/main/resources/mapper/UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectComplexQuery" resultType="User">
SELECT * FROM users
WHERE username LIKE #{pattern}
ORDER BY ${orderBy}
</select>
</mapper>
MyBatis分頁推薦使用PageHelper:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
配置示例:
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
對于多數據源場景,需要自定義配置:
@Configuration
@MapperScan(basePackages = "com.example.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class Db1DataSourceConfig {
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db1SqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/db1/*.xml"));
return bean.getObject();
}
// 類似配置第二個數據源...
}
Spring Boot默認已集成事務支持,只需在Service層添加注解:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void createUser(User user) {
userMapper.insert(user);
// 其他數據庫操作...
}
}
可能原因及解決方案:
1. 忘記添加@Mapper注解
2. 主類缺少@MapperScan掃描
3. MyBatis配置文件中mapper-locations路徑錯誤
檢查要點: - 數據庫服務是否啟動 - 連接URL格式是否正確(注意時區參數) - 用戶名密碼是否匹配
MyBatis一級緩存默認開啟,二級緩存需要顯式配置:
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 在Mapper.xml中 -->
<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
通過本文的詳細介紹,相信您已經掌握了在Spring Boot 2.0中整合MyBatis 3的核心方法。從基礎配置到高級特性,MyBatis與Spring Boot的配合能夠為項目提供靈活高效的持久層解決方案。實際開發中,建議根據項目規模選擇合適的整合方式,并注意遵循MyBatis的最佳實踐原則。
注意:本文基于Spring Boot 2.0和MyBatis 3.4編寫,不同版本可能存在配置差異,請根據實際情況調整。 “`
這篇文章共計約2350字,采用Markdown格式編寫,包含了: 1. 完整的環境搭建步驟 2. 基礎配置和代碼示例 3. 高級特性和優化建議 4. 常見問題解決方案 5. 最佳實踐指導
內容結構清晰,技術點全面,可以直接用于技術博客或開發文檔。如需調整細節或補充特定內容,可以進一步修改完善。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。