溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot 2.x整合Mybatis的方式有哪些

發布時間:2021-07-02 16:39:39 來源:億速云 閱讀:164 作者:chen 欄目:大數據
# Spring Boot 2.x整合Mybatis的方式有哪些

## 前言

MyBatis作為一款優秀的持久層框架,在Spring Boot生態中有著廣泛的應用。Spring Boot 2.x版本提供了多種與MyBatis整合的方式,開發者可以根據項目需求選擇最適合的整合方案。本文將詳細介紹三種主流整合方式及其實現細節。

## 一、官方starter整合(推薦方式)

### 1. 引入依賴

```xml
<!-- Spring Boot MyBatis官方starter -->
<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>

2. 配置數據源

# application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test_db
    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   # 實體類包路徑

3. 創建Mapper接口

@Mapper // 關鍵注解
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User findById(Long id);
}

4. 特點分析

  • 自動配置:自動創建SqlSessionFactory和SqlSessionTemplate
  • 簡化開發:無需手動編寫MyBatis配置
  • 生產推薦:適合大多數標準項目場景

二、注解方式整合(無XML配置)

1. 核心注解說明

注解 作用
@Mapper 標識MyBatis接口
@Select 定義查詢SQL
@Insert 定義插入SQL
@Update 定義更新SQL
@Delete 定義刪除SQL
@Results 結果集映射
@Result 單字段映射

2. 完整示例

@Mapper
public interface ProductMapper {
    
    @Insert("INSERT INTO products(name,price) VALUES(#{name},#{price})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Product product);
    
    @Select("SELECT * FROM products WHERE id = #{id}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "name", column = "name"),
        @Result(property = "price", column = "price")
    })
    Product selectById(Long id);
}

3. 適用場景

  • 簡單CRUD操作
  • 不希望維護XML文件的場景
  • 快速原型開發

三、XML配置方式整合

1. 項目結構

src/main/resources
├── application.yml
└── mapper
    ├── UserMapper.xml
    └── ProductMapper.xml

2. XML映射文件示例

<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="User">
        <id column="id" property="id" />
        <result column="username" property="username" />
    </resultMap>
    
    <select id="selectAll" resultMap="BaseResultMap">
        SELECT * FROM users
    </select>
</mapper>

3. 接口與XML配合

public interface UserMapper {
    List<User> selectAll(); // 方法名與XML中的id對應
}

4. 配置項說明

mybatis:
  config-location: classpath:mybatis-config.xml # 全局配置文件(可選)
  mapper-locations: classpath:mapper/**/*.xml    # 支持通配符

四、混合模式整合

1. 實現方式

@Mapper
public interface OrderMapper {
    // 注解方式
    @Select("SELECT * FROM orders WHERE id = #{id}")
    Order findSimpleOrder(Long id);
    
    // XML方式
    Order findComplexOrderWithDetails(Long id);
}
<!-- OrderMapper.xml -->
<select id="findComplexOrderWithDetails" resultMap="OrderDetailResult">
    <!-- 復雜關聯查詢 -->
</select>

2. 最佳實踐建議

  • 簡單查詢使用注解
  • 復雜查詢(動態SQL、關聯查詢)使用XML
  • 保持風格一致性

五、高級整合技巧

1. 分頁插件整合

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.1</version>
</dependency>

2. 多數據源配置

@Configuration
@MapperScan(basePackages = "com.example.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class Db1Config {
    // 配置第一個數據源...
}

@Configuration
@MapperScan(basePackages = "com.example.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class Db2Config {
    // 配置第二個數據源...
}

六、總結對比

整合方式 優點 缺點 適用場景
官方starter 開箱即用,配置簡單 定制化能力較弱 標準項目快速開發
純注解方式 無XML,代碼直觀 復雜SQL可讀性差 簡單CRUD操作
XML配置方式 復雜SQL易維護,支持動態SQL 需要維護額外文件 復雜查詢場景
混合模式 靈活平衡開發效率與維護性 風格需要統一 中大型項目

最終建議:對于新項目推薦使用官方starter+注解為主、XML為輔的混合模式,既能保證開發效率,又能應對復雜查詢需求。 “`

注:本文示例代碼基于Spring Boot 2.5.x + MyBatis 3.5.x版本,實際使用時請根據具體版本調整依賴和配置。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女