MyBatis:從入門到進階

📌 摘要

在 Java 后端開發中,MyBatis 是一個非常流行且靈活的持久層框架。它不像 Hibernate 那樣完全封裝 SQL,而是提供了對 SQL 的精細控制能力,同時又具備 ORM(對象關系映射)的功能。

本文將帶你從 MyBatis 基礎語法高級特性 全面掌握這一持久層利器,內容涵蓋:

  • MyBatis 簡介與核心優勢
  • 快速入門示例(XML 和 注解方式)
  • 映射文件詳解(resultMap、動態SQL等)
  • 與 Spring / Spring Boot 整合實戰
  • 性能優化技巧與最佳實踐
  • 常見面試題解析

適合初學者入門和中高級開發者提升技能。

  • 🔥 MyBatis中文網地址

🎯 一、為什么選擇 MyBatis?

? MyBatis 的特點:

特性描述
輕量級無侵入性,無需繼承特定類或實現接口
SQL 控制強手寫 SQL,便于性能調優
ORM 支持自動將結果集映射為 Java 對象
動態 SQL提供 <if><foreach> 等強大標簽
可擴展性強支持自定義類型處理器、插件機制
與主流框架兼容完美支持 Spring、Spring Boot

? 適用場景:

  • 對 SQL 有較高要求,需要定制化查詢
  • 數據結構復雜、需頻繁優化性能
  • 不希望被 Hibernate 的“黑盒”束縛
  • 企業項目中已有大量 SQL 腳本遷移需求

🧱 二、MyBatis 核心組件介紹

組件描述
SqlSessionFactoryBuilder構建 SqlSessionFactory 工廠對象
SqlSessionFactory創建 SqlSession 實例的核心工廠
SqlSession執行 SQL 語句并獲取映射結果的主要接口
Mapper XML 文件定義 SQL 語句和結果映射規則
Mapper 接口通過接口綁定 XML 中的 SQL
Configuration全局配置對象,包含數據源、事務管理器等信息

🚀 三、快速入門:搭建第一個 MyBatis 應用

? 開發環境準備:

  • JDK 1.8+
  • Maven 3.x
  • MySQL 5.7+
  • IDE(如 IntelliJ IDEA)

1. 添加依賴(Maven):

<!-- MyBatis -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.10</version>
</dependency><!-- MySQL驅動 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version>
</dependency>

2. 配置 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test_db?useSSL=false&amp;serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><mapper resource="mapper/UserMapper.xml"/></mappers>
</configuration>

3. 編寫實體類 User.java

public class User {private Integer id;private String name;private String email;// Getter/Setter
}

4. Mapper 接口 UserMapper.java

public interface UserMapper {User selectById(Integer id);
}

5. Mapper XML 文件 UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><select id="selectById" resultType="com.example.model.User">SELECT * FROM users WHERE id = #{id}</select>
</mapper>

6. 測試類 TestMyBatis.java

public class TestMyBatis {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.selectById(1);System.out.println(user.getName());}}
}

🛠? 四、MyBatis 進階功能詳解

1. resultMap 結果映射

適用于字段名與屬性名不一致的情況:

<resultMap id="userResultMap" type="User"><id property="id" column="user_id"/><result property="name" column="user_name"/><result property="email" column="email"/>
</resultMap><select id="selectAllUsers" resultMap="userResultMap">SELECT user_id, user_name, email FROM users
</select>

2. 動態 SQL

<if> 條件判斷:
<select id="findUsers" parameterType="map" resultType="User">SELECT * FROM users<where><if test="name != null">AND name LIKE CONCAT('%', #{name}, '%')</if><if test="email != null">AND email = #{email}</if></where>
</select>
<choose>/<when>/<otherwise> 分支判斷:
<choose><when test="name != null">AND name = #{name}</when><when test="email != null">AND email = #{email}</when><otherwise>AND status = 1</otherwise>
</choose>
<foreach> 遍歷集合:
<delete id="deleteByIds">DELETE FROM users WHERE id IN<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
</delete>

🔗 五、與 Spring / Spring Boot 整合實戰

1. Spring Boot + MyBatis 快速整合

添加依賴:
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version>
</dependency>
application.yml 配置:
spring:datasource:url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.model
Mapper 接口自動注入:
@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User selectById(Integer id);
}

🚀 六、MyBatis 高級特性與優化技巧

? 使用 PageHelper 分頁插件:

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

使用示例:

PageHelper.startPage(1, 10);
List<User> users = userMapper.selectAll();
PageInfo<User> pageInfo = new PageInfo<>(users);

? 自定義 TypeHandler 類型轉換器

public class BooleanTypeHandler implements TypeHandler<Boolean> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) {ps.setInt(i, parameter ? 1 : 0);}@Overridepublic Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {return rs.getInt(columnName) == 1;}
}

? 使用 MyBatis 插件(Interceptor)

可用于日志記錄、分頁、SQL 監控等。

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {// 前置處理邏輯System.out.println("Before executing SQL");// 執行原方法Object result = invocation.proceed();// 后置處理邏輯System.out.println("After executing SQL");return result;}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {// 可以獲取配置的屬性}
}

💬 七、常見面試題解析

Q1: MyBatis 和 Hibernate 的區別?

答:Hibernate 是全自動 ORM 框架,屏蔽 SQL;MyBatis 是半自動 ORM,需手動編寫 SQL,更靈活可控。

Q2: #{} 和 ${} 的區別?

答:#{} 是預編譯占位符,防止 SQL 注入;${} 是字符串替換,存在注入風險。

Q3: 如何實現批量插入?

答:使用 <foreach> 標簽拼接多條 INSERT 語句,或結合 JDBC 的批處理。

Q4: 如何防止 N+1 查詢問題?

答:使用 <association><collection> 嵌套查詢,并啟用延遲加載(lazyLoadingEnabled)。

Q5: MyBatis 如何實現緩存?

答:一級緩存默認開啟(SqlSession級別),二級緩存需手動配置(Mapper級別)。


💡 八、總結

通過本文的學習,你應該已經掌握了:

  • MyBatis 的基本原理與使用方式
  • 如何使用 XML 或注解方式進行 CRUD 操作
  • 動態 SQL 的編寫技巧
  • resultMap 的使用與映射優化
  • 與 Spring / Spring Boot 的整合方法
  • 高級特性如分頁、插件、自定義類型處理器
  • 常見面試題解析

MyBatis 是 Java 持久層開發中的利器,既能保持靈活性,又能兼顧開發效率,是構建高性能后端系統的首選之一。



  • 如果你在學習過程中遇到任何疑問,歡迎在評論區留言交流!
  • 👍 如果你覺得這篇文章對你有幫助,別忘了點贊、收藏、轉發哦!

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

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

相關文章

leetcode51.N皇后:回溯算法與沖突檢測的核心邏輯

一、題目深度解析與N皇后問題本質 題目描述 n皇后問題研究的是如何將n個皇后放置在nn的棋盤上&#xff0c;并且使皇后彼此之間不能相互攻擊。給定一個整數n&#xff0c;返回所有不同的n皇后問題的解決方案。每一種解法包含一個明確的n皇后問題的棋子放置方案&#xff0c;該方…

算法-每日一題(DAY9)楊輝三角

1.題目鏈接&#xff1a; 118. 楊輝三角 - 力扣&#xff08;LeetCode&#xff09; 2.題目描述&#xff1a; 給定一個非負整數 numRows&#xff0c;生成「楊輝三角」的前 numRows 行。 在「楊輝三角」中&#xff0c;每個數是它左上方和右上方的數的和。 示例 1: 輸入: numRo…

【MATLAB代碼】制導方法介紹與例程——追蹤法,適用于二維平面,目標是移動的|附完整源代碼

追蹤法(追蹤導引法)是一種常見的導彈導引方式,其基本原理是保持導彈的速度矢量始終指向目標。在追蹤法中,導彈的加速度可以表示為指向目標的加速度。 本文給出二維平面下,移動目標的追蹤法導引的介紹、公式與matlab例程 訂閱專欄后,可以直接查看完整源代碼 文章目錄 運行…

小白的進階之路系列之十八----人工智能從初步到精通pytorch綜合運用的講解第十一部分

從零開始的NLP:使用序列到序列網絡和注意力機制進行翻譯 我們將編寫自己的類和函數來預處理數據以完成我們的 NLP 建模任務。 在這個項目中,我們將訓練一個神經網絡將法語翻譯成英語。 [KEY: > input, = target, < output]> il est en train de peindre un table…

SSL安全證書:數字時代的網絡安全基石

SSL安全證書&#xff1a;數字時代的網絡安全基石 在當今數字化浪潮中&#xff0c;網絡通信安全已成為個人、企業和組織不可忽視的核心議題。SSL&#xff08;Secure Sockets Layer&#xff0c;安全套接層&#xff09;安全證書作為保障數據傳輸安全的關鍵技術&#xff0c;通過加…

LLM-201: OpenHands與LLM交互鏈路分析

一、核心交互鏈路架構 #mermaid-svg-ZBqCSQk1PPDkIXNx {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-ZBqCSQk1PPDkIXNx .error-icon{fill:#552222;}#mermaid-svg-ZBqCSQk1PPDkIXNx .error-text{fill:#552222;strok…

【項目】仿muduo庫one thread one loop式并發服務器SERVER模塊(下)

&#x1f4da; 博主的專欄 &#x1f427; Linux | &#x1f5a5;? C | &#x1f4ca; 數據結構 | &#x1f4a1;C 算法 | &#x1f152; C 語言 | &#x1f310; 計算機網絡 |&#x1f5c3;? mysql 項目文章&#xff1a; 仿muduo庫one thread one loop式并發服務器…

數據庫索引結構 B 樹、B + 樹與哈希索引在不同數據查詢場景下的適用性分析

一、數據庫索引結構B樹 樹概述 樹是一種多路平衡查找樹&#xff0c;廣泛應用于數據庫和文件系統中。B樹的節點可以存儲多個數據元素&#xff0c;并且保持樹的平衡&#xff0c;以提高查詢效率。 適用性分析 在數據量較大&#xff0c;范圍查找較多的場景下&#xff0c;B樹的查詢效…

Linux進程間通信——信號

1.信號的介紹 信號( Signal )是 Unix, 類Unix以及其他POSIX兼容的操作系統中進程間通信的一種有限制的手段。 1&#xff09;信號是在軟件層面上對中斷機制的一種模擬&#xff0c;是一種異步通信方式。2&#xff09;信號可以直接進行用戶空間進程和內核進程之間的交互&#xff…

Bytemd@Bytemd/react詳解(編輯器實現基礎AST、插件、跨框架)

ByteMD Markdown編輯器詳細解釋&修改編輯器默認樣式&#xff08;高度300px) AST樹詳解 [ByteMD 插件系統詳解(https://blog.csdn.net/m0_55049655/article/details/148811248?spm1001.2014.3001.5501) Sevelet編寫的Bytemd如何適配到React中 ??1?? 背景概述 Byte…

《Redis》事務

文章目錄 Redis中的原子性Redis的事物和MySQL事務的區別Redis實現事務什么場景下&#xff0c;會使用事務? Redis事務相關命令watch命令的實現原理 總結 Redis中的原子性 Redis的原子性不同于MySQL的原子性。 Redis的事物和MySQL事務的區別 但是注意體會Redis的事務和MySQL…

Elasticsearch Kibana (一)

一、官方文檔 elasticsearch官網&#xff1a;elasticsearch官網 elasticsearch源碼&#xff1a;elasticsearch源碼 ik分詞器&#xff1a; ik分詞器 ik分詞器下載&#xff1a;ik分詞器下載 elasticsearch 版本選擇&#xff1a;elasticsearch 版本選擇 官方推薦Elasticsearch和j…

[linux] Ubuntu 24軟件下載和安裝匯總(自用)

經常重裝系統&#xff0c;備份下&#xff0c;有用的也可以參考。 安裝圖形界面 apt install ubuntu-desktop systemctl set-default graphical.target reboot 安裝chrome wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo apt insta…

分布變化的模仿學習算法

與傳統監督學習不同,直接模仿學習在不同時刻所面臨的數據分布可能不同.試設計一個考慮不同時刻數據分布變化的模仿學習算法 import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from…

arm-none-eabi-ld: cannot find -lm

arm-none-eabi-ld -Tuser/hc32l13x.lds -o grbl_hc32l13x.elf user/interrupts_hc32l13x.o user/system_hc32l13x.o user/main.o user/startup_hc32l13x.o -lm -Mapgrbl_hc32l13x.map arm-none-eabi-ld: cannot find -lm makefile:33: recipe for target link failed 改為在gcc…

【Python辦公】Excel文件批量樣式修改器

目錄 專欄導讀1. 背景介紹2. 項目概述3. 庫的安裝4. 核心架構設計① 類結構設計② 數據模型1) 文件管理2) 樣式配置5. 界面設計與實現① 布局結構② 動態組件生成6. 核心功能實現① 文件選擇與管理② 顏色選擇功能③ Excel文件處理核心邏輯完整代碼結尾專欄導讀 ?? 歡迎來到P…

QT的一些介紹

//雖然下面一行代碼進行widget和ui的窗口關聯&#xff0c;但是如果發生窗口大小變化的時候&#xff0c;里面的布局不會隨之變化ui->setupUi(this);//通過下面這行代碼進行顯示說明&#xff0c;讓窗口變化時&#xff0c;布局及其子控件隨之變化this->setLayout(ui->ver…

RISC-V向量擴展與GPU協處理:開源加速器設計新范式——對比NVDLA與香山架構的指令集融合方案

點擊 “AladdinEdu&#xff0c;同學們用得起的【H卡】算力平臺”&#xff0c;H卡級別算力&#xff0c;按量計費&#xff0c;靈活彈性&#xff0c;頂級配置&#xff0c;學生專屬優惠 當開源指令集遇上異構計算&#xff0c;RISC-V向量擴展&#xff08;RVV&#xff09;正重塑加速…

自動恢復網絡路由配置的安全腳本說明

背景 兩個文章 看了就明白 Ubuntu 多網卡路由配置筆記&#xff08;內網 外網同時通 可能有問題&#xff0c;以防萬一可以按照個來恢復 sudo ip route replace 192.168.1.0/24 dev eno8403 proto kernel scope link src <你的IP>或者恢復腳本! 如下 誤操作路由時&…

創建 Vue 3.0 項目的兩種方法對比:npm init vue@latest vs npm init vite@latest

創建 Vue 3.0 項目的兩種方法對比&#xff1a;npm init vuelatest vs npm init vitelatest Vue 3.0 作為當前主流的前端框架&#xff0c;官方提供了多種項目創建方式。本文將詳細介紹兩種最常用的創建方法&#xff1a;Vue CLI 方式 (npm init vuelatest) 和 Vite 方式 (npm in…