【SpringBoot核心】Spring Boot + MyBatis 深度整合與最佳實踐

目錄

  1. 引言
  2. Spring Boot 基礎回顧
  3. MyBatis 核心概念解析
  4. Spring Boot 整合 MyBatis
  5. MyBatis 高級特性
  6. Spring Boot + MyBatis 最佳實踐
  7. 性能優化與擴展
  8. 實戰案例:電商系統開發
  9. 常見問題與解決方案
  10. 總結與展望

1. 引言

1.1 技術背景與現狀

在現代企業級應用開發中,數據持久化是一個核心需求。隨著Java生態系統的不斷發展,出現了多種ORM框架,如Hibernate、MyBatis、JPA等。其中,MyBatis因其靈活性、高性能和易用性,在企業級應用中占據了重要地位。

Spring Boot作為Spring框架的"約定優于配置"實現,極大地簡化了Spring應用的初始搭建和開發過程。將Spring Boot與MyBatis結合,可以充分發揮兩者的優勢,構建高效、可維護的數據訪問層。

1.2 為什么選擇Spring Boot + MyBatis

  1. 開發效率高:Spring Boot的自動配置和起步依賴大大減少了樣板代碼
  2. 靈活性好:MyBatis允許開發者直接編寫SQL,保持了對SQL的完全控制
  3. 性能優異:MyBatis避免了Hibernate等框架可能產生的復雜查詢問題
  4. 易于集成:Spring Boot對MyBatis有良好的官方支持
  5. 生態豐富:兩者都有龐大的社區和豐富的插件支持

1.3 本文內容概覽

本文將全面介紹Spring Boot與MyBatis的整合與實踐,從基礎配置到高級特性,再到性能優化和實戰案例,為開發者提供一站式解決方案。

2. Spring Boot 基礎回顧

2.1 Spring Boot 核心特性

Spring Boot的核心設計理念是"約定優于配置",其主要特性包括:

  1. 自動配置:根據classpath中的jar包自動配置Spring應用
  2. 起步依賴:簡化Maven/Gradle配置,一鍵式添加功能模塊
  3. Actuator:提供生產級監控和管理端點
  4. 嵌入式容器:內置Tomcat、Jetty等Servlet容器
  5. 外部化配置:支持多種格式的配置文件和環境變量

2.2 Spring Boot 項目結構

標準的Spring Boot項目結構如下:

src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── demo/
│   │               ├── DemoApplication.java       # 啟動類
│   │               ├── config/                   # 配置類
│   │               ├── controller/               # 控制器
│   │               ├── service/                  # 服務層
│   │               ├── dao/                      # 數據訪問層
│   │               └── model/                    # 實體類
│   └── resources/
│       ├── static/                               # 靜態資源
│       ├── templates/                            # 模板文件
│       ├── application.yml                       # 主配置文件
│       └── mapper/                               # MyBatis映射文件
└── test/                                         # 測試代碼

2.3 Spring Boot 自動配置原理

Spring Boot的自動配置是通過@EnableAutoConfiguration注解實現的,其核心機制包括:

  1. 條件注解:如@ConditionalOnClass@ConditionalOnMissingBean
  2. 自動配置類:位于META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  3. 配置屬性:通過@ConfigurationProperties綁定外部配置

示例:查看自動配置報告

# 啟用debug日志查看自動配置報告
logging.level.root=debug

或者在啟動時添加--debug參數:

java -jar myapp.jar --debug

3. MyBatis 核心概念解析

3.1 MyBatis 架構概述

MyBatis的整體架構分為三層:

  1. 基礎支撐層:事務管理、連接池、緩存、日志等基礎設施
  2. 核心處理層:配置解析、參數映射、SQL解析、SQL執行、結果集映射
  3. 接口層:SqlSession API、Mapper接口

3.2 核心組件詳解

3.2.1 SqlSessionFactory

SqlSessionFactory是MyBatis的核心對象,用于創建SqlSession。通常一個應用只需要一個SqlSessionFactory實例。

構建方式:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.2.2 SqlSession

SqlSession代表一次數據庫會話,線程不安全,每次使用后應該關閉。主要方法包括:

  • selectOne():查詢單個對象
  • selectList():查詢對象列表
  • insert():插入數據
  • update():更新數據
  • delete():刪除數據
  • commit():提交事務
  • rollback():回滾事務
3.2.3 Mapper 接口

Mapper接口是MyBatis的核心概念之一,通過動態代理技術將接口方法與SQL語句綁定。示例:

public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User selectUser(int id);
}

3.3 XML 映射文件

MyBatis的XML映射文件包含以下主要元素:

  1. <select>:查詢語句
  2. <insert>:插入語句
  3. <update>:更新語句
  4. <delete>:刪除語句
  5. <sql>:可重用的SQL片段
  6. <resultMap>:結果集映射

示例:

<mapper namespace="com.example.mapper.UserMapper"><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="email" column="email"/></resultMap><select id="selectUser" resultMap="userResultMap">SELECT * FROM users WHERE id = #{id}</select>
</mapper>

3.4 動態SQL

MyBatis提供了強大的動態SQL功能,主要元素包括:

  1. <if>:條件判斷
  2. <choose>/<when>/<otherwise>:多條件選擇
  3. <trim>/<where>/<set>:輔助處理SQL片段
  4. <foreach>:循環遍歷集合

示例:

<select id="findUsers" resultType="User">SELECT * FROM users<where><if test="username != null">AND username like #{username}</if><if test="email != null">AND email = #{email}</if></where>
</select>

4. Spring Boot 整合 MyBatis

4.1 項目初始化

4.1.1 使用Spring Initializr創建項目

可以通過https://start.spring.io或IDE插件創建Spring Boot項目,添加以下依賴:

  • Spring Web
  • MyBatis Framework
  • MySQL Driver (或其他數據庫驅動)
  • Lombok (可選,簡化代碼)
4.1.2 Maven依賴配置
<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MyBatis Starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version></dependency><!-- MySQL Connector --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

4.2 基礎配置

4.2.1 數據源配置

application.yml中配置數據源:

spring:datasource:url: jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC&characterEncoding=utf8username: rootpassword: passworddriver-class-name: com.mysql.cj.jdbc.Driverhikari:pool-name: HikariCPmaximum-pool-size: 20minimum-idle: 10idle-timeout: 30000max-lifetime: 60000connection-timeout: 30000
4.2.2 MyBatis 基本配置
mybatis:mapper-locations: classpath:mapper/*.xml  # XML映射文件位置type-aliases-package: com.example.model   # 實體類包名configuration:map-underscore-to-camel-case: true     # 自動駝峰命名轉換default-fetch-size: 100                # 默認獲取數量default-statement-timeout: 30           # 超時時間(秒)

4.3 基礎CRUD實現

4.3.1 實體類定義
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String username;private String password;private String email;private Date createTime;private Date updateTime;
}
4.3.2 Mapper接口定義
@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO users(username, password, email, create_time, update_time) " +"VALUES(#{username}, #{password}, #{email}, now(), now())")@Options(useGeneratedKeys = true, keyProperty = "id")int insert(User user);@Update("UPDATE users SET username=#{username}, email=#{email}, update_time=now() WHERE id=#{id}")int update(User user);@Delete("DELETE FROM users WHERE id=#{id}")int delete(Long id);@Select("SELECT * FROM users")List<User> findAll();
}
4.3.3 Service層實現
@Service
@RequiredArgsConstructor
public class UserService {private final UserMapper userMapper;public User getUserById(Long id) {return userMapper.findById(id);}public List<User> getAllUsers() {return userMapper.findAll();}public int createUser(User user) {return userMapper.insert(user);}public int updateUser(User user) {return userMapper.update(user);}public int deleteUser(Long id) {return userMapper.delete(id);}
}
4.3.4 Controller層實現
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {private final UserService userService;@GetMapping("/{id}")public ResponseEntity<User> getUser(@PathVariable Long id) {User user = userService.getUserById(id);return ResponseEntity.ok(user);}@GetMappingpublic ResponseEntity<List<User>> getAllUsers() {List<User> users = userService.getAllUsers();return ResponseEntity.ok(users);}@PostMappingpublic ResponseEntity<Void> createUser(@RequestBody User user) {userService.createUser(user);return ResponseEntity.status(HttpStatus.CREATED).build();}@PutMapping("/{id}")public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);return ResponseEntity.ok().build();}@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {userService.deleteUser(id);return ResponseEntity.noContent().build();}
}

4.4 XML映射方式實現

4.4.1 創建XML映射文件

resources/mapper目錄下創建UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.UserMapper"><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="password" column="password"/><result property="email" column="email"/><result property="createTime" column="create_time"/><result property="updateTime" column="update_time"/></resultMap><select id="findById" resultMap="userResultMap">SELECT * FROM users WHERE id = #{id}</select><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO users(username, password, email, create_time, update_time)VALUES(#{username}, #{password}, #{email}, now(), now())</insert><update id="update" parameterType="User">UPDATE users SET username=#{username}, email=#{email}, update_time=now()WHERE id=#{id}</update><delete id="delete">DELETE FROM users WHERE id=#{id}</delete><select id="findAll" resultMap="userResultMap">SELECT * FROM users</select>
</mapper>
4.4.2 修改Mapper接口
@Mapper
public interface UserMapper {User findById(Long id);int insert(User user);int update(User user);int delete(Long id);List<User> findAll();
}

4.5 分頁查詢實現

4.5.1 添加分頁依賴
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>2.1.0</version>
</dependency>
4.5.2 配置分頁插件
pagehelper:helper-dialect: mysqlreasonable: truesupport-methods-arguments: trueparams: count=countSql
4.5.3 實現分頁查詢
@Service
@RequiredArgsConstructor
public class UserService {private final UserMapper userMapper;public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);List<User> users = userMapper.findAll();return new PageInfo<>(users);}
}@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {private final UserService userService;@GetMapping("/page")public ResponseEntity<PageInfo<User>> getUsersByPage(@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "10") int pageSize) {PageInfo<User> pageInfo = userService.getUsersByPage(pageNum, pageSize);return ResponseEntity.ok(pageInfo);}
}

5. MyBatis 高級特性

5.1 動態SQL高級用法

5.1.1 <choose>/<when>/<otherwise>示例
<select id

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/89100.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/89100.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/89100.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

力扣第77題-組合-力扣第78題-子集

力扣鏈接:77. 組合 - 力扣&#xff08;LeetCode&#xff09; 給定兩個整數 n 和 k&#xff0c;返回范圍 [1, n] 中所有可能的 k 個數的組合。 你可以按 任何順序 返回答案。 示例 1&#xff1a; 輸入&#xff1a;n 4, k 2 輸出&#xff1a; [[2,4],[3,4],[2,3],[1,2],[1,3…

嵌入式MTD設備與Flash管理解析

理解MTD是嵌入式系統中處理Flash存儲的關鍵一步&#xff01;我來幫你梳理清楚&#xff1a; MTD 是什么&#xff1f; MTD 是 Memory Technology Device 的縮寫&#xff0c;中文常譯為內存技術設備。它是 Linux 內核及其衍生系統&#xff08;如嵌入式 Linux&#xff09;中用于管…

基于 GEE 利用 Sentinel-2 數據計算并下載植被指數數據

目錄 1 植被指數 2 完整代碼 3 運行結果 1 植被指數 植被指數全名NDVI歸一化差值植被指數GNDVI綠色歸一化差值植被指數EVI增強植被指數EVI2雙波段增強植被指數DVI差值植被指數GDVI綠色差植被值指數RVI比值植被指數SAVI土壤調整植被指數OSAVI優化土壤調整植被指數MSAVI修改…

python基礎23(2025.6.29)分布式爬蟲(增量式爬蟲去重)redis應用_(未完成!)

本次寫一個爬取網易新聞的案例。因為redis能處理高并發&#xff0c;存儲數據也可以&#xff0c;故不用mysql。而且新聞網站容易更新很多&#xff0c;而mysql只能持久化存儲。 import scrapy import re import json import redis # 用它來去除重復, 記錄訪問過的urlclass Wang…

Springboot 集成 SpringState 狀態機

Springboot 集成 SpringState 狀態機 1.SpringState 簡介2.狀態機示例2.1 項目結構和依賴包2.2 定義事件類和狀態類2.3 Spring 事件監聽器2.4 狀態機持久化類2.4.1 Redis 狀態機持久化容器2.4.2 Redis 配置2.4.3 狀態機監聽器 2.5 裝機器容器2.6 狀態機事件發送器2.7 狀態機配置…

實戰四:基于PyTorch實現貓狗分類的web應用【2/3】

?一、需求描述 實戰四分為三部分來實現&#xff0c;第二部分是基于PyTorch的貓狗圖像可視化訓練的教程&#xff0c;實現了一個完整的貓狗分類模型訓練流程&#xff0c;使用預訓練的ResNet50模型進行遷移學習&#xff0c;并通過SwanLab進行實驗跟蹤。 效果圖 ?二、實現思路 …

對比幾個測試云的一些速度

最近被hosting vps主機的速度給困擾了&#xff0c;干脆放下手中的活 測試下 test.php放在網站根目錄即可 代碼如下&#xff1a; <?php /*** 最終版服務器性能測試工具* 測試項目&#xff1a;CPU運算性能、內存讀寫速度、硬盤IO速度、網絡下載速度*/// 配置參數&#xff…

UE5 Grid3D 學習筆記

一、Neighbor Grid 3D 的核心作用 NeighborGrid3D 是一種基于位置的哈希查找結構&#xff0c;將粒子按空間位置劃分到網格單元&#xff08;Cell&#xff09;中&#xff0c;實現快速鄰近查詢&#xff1a; 空間劃分&#xff1a;將模擬空間劃分為多個三維網格單元&#xff08;Cel…

Spring AI ——在springboot應用中實現基本聊天功能

文章目錄 前言測試環境項目構建依賴引入指定openai 相關配置基于 application.yml 配置 Open AI 屬性application.yml編寫測試類測試請求基于讀取后配置請求編寫測試接口測試效果展示流式輸出前言 AI 技術越來越火爆,作為Java開發人員也不能拖了后腿。 前段時間使用LangChain…

條件概率:不確定性決策的基石

條件概率是概率論中的核心概念&#xff0c;用于描述在已知某一事件發生的條件下&#xff0c;另一事件發生的概率。它量化了事件之間的關聯性&#xff0c;是貝葉斯推理、統計建模和機器學習的基礎。 本文由「大千AI助手」原創發布&#xff0c;專注用真話講AI&#xff0c;回歸技術…

搭建Flink分布式集群

1. 基礎環境&#xff1a; 1.1 安裝JDK 本次使用 jdk-11.0.26_linux-x64_bin.tar.gz 解壓縮 tar -zxvf jdk-11.0.26_linux-x64_bin.tar.gz -C /usr/local/java/ 配置環境變量&#xff1a; vi /etc/profileJAVA_HOME/usr/local/java/jdk-11.0.26 CLASSPATH.:${JAVA_HOME}/li…

基于ssm校園綜合服務系統微信小程序源碼數據庫文檔

摘 要 隨著我國經濟迅速發展&#xff0c;人們對手機的需求越來越大&#xff0c;各種手機軟件也都在被廣泛應用&#xff0c;但是對于手機進行數據信息管理&#xff0c;對于手機的各種軟件也是備受用戶的喜愛&#xff0c;校園綜合服務被用戶普遍使用&#xff0c;為方便用戶能夠可…

桌面小屏幕實戰課程:DesktopScreen 17 HTTPS

飛書文檔http://https://x509p6c8to.feishu.cn/docx/doxcn8qjiNXmw2r3vBEdc7XCBCh 源碼參考&#xff1a; /home/kemp/work/esp/esp-idf/examples/protocols/https_request 源碼下載方式參考&#xff1a; 源碼下載方式 獲取網站ca證書 openssl s_client -showcerts -connec…

uniapp上傳gitee

右鍵點擊項目&#xff0c;選擇git提交&#xff0c;會彈出這樣的彈窗 在Message輸入框里面輸入更新的內容&#xff0c;選擇更新過的文件&#xff0c;然后點擊commit 然后點擊push 后面會讓你填寫gitee的用戶名和密碼 用戶名就是郵箱 密碼就是登錄gitee的密碼

重寫(Override)與重載(Overload)深度解析

在Java面向對象編程中&#xff0c;多態性是一個核心概念&#xff0c;它允許我們以統一的方式處理不同類型的對象。而實現多態性的兩種重要機制便是方法的“重寫”&#xff08;Override&#xff09;與“重載”&#xff08;Overload&#xff09;。透徹理解這兩者之間的區別與聯系…

Go 語言中操作 SQLite

sqlite以其無需安裝和配置&#xff1a;直接使用數據庫文件&#xff0c;無需啟動獨立的數據庫服務進程。 單文件存儲&#xff1a;整個數據庫&#xff08;包括表、索引、數據等&#xff09;存儲在單個跨平臺文件中&#xff0c;便于遷移和備份。 在應對的小型應用軟件中.有著不可…

【硬核數學】2.3 AI的“想象力”:概率深度學習與生成模型《從零構建機器學習、深度學習到LLM的數學認知》

歡迎來到本系列的第八篇文章。在前七章中&#xff0c;我們已經構建了一個強大的深度學習工具箱&#xff1a;我們用張量來處理高維數據&#xff0c;用反向傳播來高效地計算梯度&#xff0c;用梯度下降來優化模型參數。我們訓練出的模型在分類、回歸等任務上表現出色。 但它們有…

華為云Flexus+DeepSeek征文|Dify平臺開發搭建口腔牙科24小時在線問診系統(AI知識庫系統)

引言&#xff1a;為什么需要口腔牙科24小時在線問診系統&#xff1f; 在口腔醫療領域&#xff0c;“時間”是患者最敏感的需求之一——深夜牙齒突發疼痛、周末想提前了解治療方案、異地患者無法及時到院……傳統“工作時間在線”的咨詢模式已無法滿足用戶需求。同時&#xff0…

嵌入式硬件中電容的基本原理與詳解

大家好我們今天重討論點知識點如下: 1.電容在電路中的作用 2.用生活中水缸的例子來比喻電容 3.電容存儲能力原理 4.電容封裝的種類介紹電容種類圖片辨識 5.X 電容的作用介紹 6.Y 電容的作用介紹7.鉭電容的優點及特性 7.鉭電容的缺點及特性 8. 鋁電解電容的優點及特性…

中央空調控制系統深度解析:從原理到智能AIOT運維

——附水冷式系統全電路圖解與技術參數 一、中央空調系統架構與技術演進 1. 兩大主流系統對比 技術趨勢&#xff1a;2023年全球冷水機組市場占比達68%&#xff08;BSRIA數據&#xff09;&#xff0c;其核心優勢在于&#xff1a; - 分區控溫精度&#xff1a;0.5℃&#…