溫馨提示×

溫馨提示×

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

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

springboot2.0中怎么整合mybatis3

發布時間:2021-07-30 14:20:44 來源:億速云 閱讀:158 作者:Leah 欄目:大數據
# 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>

1.2 添加MyBatis相關依賴

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>

二、基礎整合配置

2.1 數據源配置

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

2.2 MyBatis基本配置

mybatis:
  mapper-locations: classpath:mapper/*.xml  # XML映射文件位置
  type-aliases-package: com.example.model    # 實體類包路徑
  configuration:
    map-underscore-to-camel-case: true     # 開啟駝峰命名轉換

三、代碼實現

3.1 實體類創建

package com.example.model;

public class User {
    private Long id;
    private String username;
    private String email;
    
    // 省略getter/setter
}

3.2 Mapper接口定義

@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);
    
    // 更多方法...
}

3.3 XML映射文件(可選)

對于復雜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>

四、高級配置與優化

4.1 分頁插件集成

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

4.2 多數據源配置

對于多數據源場景,需要自定義配置:

@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();
    }
    
    // 類似配置第二個數據源...
}

4.3 事務管理

Spring Boot默認已集成事務支持,只需在Service層添加注解:

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Transactional
    public void createUser(User user) {
        userMapper.insert(user);
        // 其他數據庫操作...
    }
}

五、常見問題解決

5.1 Mapper接口無法注入

可能原因及解決方案: 1. 忘記添加@Mapper注解 2. 主類缺少@MapperScan掃描 3. MyBatis配置文件中mapper-locations路徑錯誤

5.2 數據庫連接問題

檢查要點: - 數據庫服務是否啟動 - 連接URL格式是否正確(注意時區參數) - 用戶名密碼是否匹配

5.3 緩存配置

MyBatis一級緩存默認開啟,二級緩存需要顯式配置:

<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>

<!-- 在Mapper.xml中 -->
<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>

六、最佳實踐建議

  1. SQL管理:簡單SQL使用注解,復雜SQL使用XML
  2. 事務粒度:保持事務方法盡可能小
  3. 性能監控:集成Druid監控SQL性能
  4. 代碼生成:使用MyBatis Generator自動生成基礎代碼
  5. 版本控制:保持MyBatis與Spring Boot版本兼容

結語

通過本文的詳細介紹,相信您已經掌握了在Spring Boot 2.0中整合MyBatis 3的核心方法。從基礎配置到高級特性,MyBatis與Spring Boot的配合能夠為項目提供靈活高效的持久層解決方案。實際開發中,建議根據項目規模選擇合適的整合方式,并注意遵循MyBatis的最佳實踐原則。

注意:本文基于Spring Boot 2.0和MyBatis 3.4編寫,不同版本可能存在配置差異,請根據實際情況調整。 “`

這篇文章共計約2350字,采用Markdown格式編寫,包含了: 1. 完整的環境搭建步驟 2. 基礎配置和代碼示例 3. 高級特性和優化建議 4. 常見問題解決方案 5. 最佳實踐指導

內容結構清晰,技術點全面,可以直接用于技術博客或開發文檔。如需調整細節或補充特定內容,可以進一步修改完善。

向AI問一下細節

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

AI

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