MyBatis 詳解及代碼示例

MyBatis 是一個 半自動 ORM 框架,主要用于 Java 與數據庫之間的持久化操作,它本質是對 JDBC 的封裝

  • 全名:MyBatis(前身 iBATIS)
  • 核心作用:自動將 SQL 執行結果映射為 Java 對象;也可以將 Java 對象自動轉成 SQL 參數
  • 特點
    • SQL 寫在 XML 或注解中,開發者可控制 SQL 邏輯(相比 Hibernate 更靈活)
    • 支持參數映射、結果映射
    • 支持動態 SQL(根據條件生成 SQL)

🏗? 1. 在 SpringMVC 項目中的使用步驟


🌱 一、技術棧說明

  • Spring MVC(控制層)
  • MyBatis(持久層)
  • Spring(IoC、事務管理)
  • MySQL 數據庫
  • Maven 構建

🧱 二、項目結構示意(SpringMVC 示例)

spring-mybatis-demo/
├── src/main/java/
│   ├── com.example.controller/     # 控制層
│   ├── com.example.service/        # 業務邏輯
│   ├── com.example.mapper/         # MyBatis Mapper 接口
│   ├── com.example.model/          # 實體類
│   └── com.example.config/         # 配置類(可選)
├── src/main/resources/
│   ├── mapper/                     # MyBatis XML 映射文件
│   ├── spring-mybatis.xml          # 核心整合配置
│   └── db.properties               # 數據源配置
├── webapp/
│   ├── WEB-INF/
│   │   ├── jsp/                    # 視圖層 JSP
│   │   └── web.xml                 # Web 配置
└── pom.xml

📦 三、核心配置文件

3.1 pom.xml(關鍵依賴)
<dependencies><!-- Spring 核心依賴 --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId><version>5.3.30</version></dependency><!-- MyBatis --><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.15</version> </dependency><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.1.1</version> </dependency><!-- MySQL 驅動 --><dependency><groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency><!-- 其他:日志、JSTL、Servlet 等 -->
</dependencies>

3.2 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.username=root
jdbc.password=123456

3.3 spring-mybatis.xml(Spring + MyBatis 整合配置)
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="..."><!-- 1. 讀取屬性配置 --><context:property-placeholder location="classpath:db.properties"/><!-- 2. 配置數據源 --><bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!-- 3. 配置 SqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:mapper/*.xml"/><property name="typeAliasesPackage" value="com.example.model"/></bean><!-- 4. Mapper 接口掃描 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.example.mapper"/></bean><!-- 5. 掃描 Service、Controller --><context:component-scan base-package="com.example"/><!-- 6. 事務管理 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

3.4 web.xml 配置 Spring MVC 和核心監聽器
<web-app ...><!-- Spring 容器監聽器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml</param-value></context-param><!-- Spring MVC 核心配置 --><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>

💻 四、代碼示例

4.1 實體類 User.java
public class User {private Integer id;private String name;private Integer age;// Getter / Setter
}

4.2 Mapper 接口 UserMapper.java
java復制編輯public interface UserMapper {User selectById(Integer id);List<User> selectAll();
}

4.3 Mapper XML 文件 UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper"><select id="selectById" resultType="User">SELECT * FROM user WHERE id = #{id}</select><select id="selectAll" resultType="User">SELECT * FROM user</select>
</mapper>

4.4 Service 類
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUser(Integer id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.selectAll();}
}

4.5 Controller 類
@Controller
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/list")public String list(Model model) {List<User> users = userService.getAllUsers();model.addAttribute("users", users);return "userList"; // 對應 userList.jsp}
}

4.6 JSP 頁面(視圖層)userList.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h2>User List</h2>
<table border="1"><tr><th>ID</th><th>Name</th><th>Age</th></tr><c:forEach var="u" items="${users}"><tr><td>${u.id}</td><td>${u.name}</td><td>${u.age}</td></tr></c:forEach>
</table>
</body>
</html>

💡 五、動態 SQL 示例(補充)

可以在 UserMapper.xml 中這樣寫:

<select id="searchUser" resultType="User">SELECT * FROM user<where><if test="name != null and name != ''">AND name LIKE CONCAT('%', #{name}, '%')</if><if test="age != null">AND age = #{age}</if></where>
</select>

調用時只傳入某些字段,MyBatis 會自動拼接對應 SQL 語句。


📌 六、總結

內容說明
Spring MVC控制器接收請求,返回視圖
MyBatis封裝了 JDBC,實現 SQL 到 Java 映射
配置方式XML 文件整合(spring-mybatis.xmlmapper.xml
特點靈活、輕量、適合手寫 SQL

在 SpringBoot 項目中的使用步驟

一、項目結構

1.1 引入依賴(Maven)
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.0</version>
</dependency>
1.2 配置 application.yml
spring:datasource:url: jdbc:mysql://localhost:3306/testdbusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.modelconfiguration:map-underscore-to-camel-case: true
2.3 編寫實體類
public class User {private Integer id;private String name;private Integer age;// getter/setter...
}
2.4 編寫 Mapper 接口
@Mapper
public interface UserMapper {User selectUserById(Integer id);List<User> selectAllUsers();
}
2.5 編寫 Mapper.xml(放在 resources/mapper/UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper"><select id="selectUserById" resultType="User">SELECT * FROM user WHERE id = #{id}</select><select id="selectAllUsers" resultType="User">SELECT * FROM user</select>
</mapper>
2.6 Service 和 Controller 層調用
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUser(Integer id) {return userMapper.selectUserById(id);}
}

?? 2. 配置文件詳解(MyBatis 配置)

除了 application.yml 中配置項,MyBatis 也支持獨立 XML 配置(mybatis-config.xml),示例:

<configuration><settings><!-- 駝峰命名自動映射 --><setting name="mapUnderscoreToCamelCase" value="true"/></settings><typeAliases><package name="com.example.model"/></typeAliases><mappers><mapper resource="mapper/UserMapper.xml"/></mappers>
</configuration>

這些配置項在 Spring Boot 項目中一般都寫在 application.yml


🧱 3. 核心組件說明

組件作用說明
SqlSessionMyBatis 的 SQL 會話對象,封裝了 JDBC 操作
Mapper 接口定義與數據庫交互的方法
XML Mapper 文件定義 SQL 語句,與接口方法一一對應
TypeHandler類型處理器,用于 Java 類型與 JDBC 類型互相轉換
ExecutorMyBatis 的 SQL 執行器,控制 SQL 執行流程
Configuration全局配置對象,保存所有配置信息

🧠 4. 動態 SQL(重點)

動態 SQL 是 MyBatis 的亮點之一,常用標簽如下:

4.1 <if>

<if test="name != null">AND name = #{name}
</if>

4.2 <where>

自動拼接 WHERE,去掉多余 AND/OR:

<where><if test="name != null"> AND name = #{name} </if><if test="age != null"> AND age = #{age} </if>
</where>

4.3 <set>

用于動態生成 UPDATE SET,避免多余逗號:

<set><if test="name != null"> name = #{name}, </if><if test="age != null"> age = #{age} </if>
</set>

4.4 <foreach>

用于 IN 查詢等場景:

<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}
</foreach>

4.5 <choose> <when> <otherwise>

<choose><when test="type == 'admin'"> AND role = 'ADMIN' </when><otherwise> AND role = 'GUEST' </otherwise>
</choose>

? 5. 優缺點總結

? 優點

  • SQL 可控,適合復雜業務
  • 支持動態 SQL、注解與 XML 并存
  • 易于與 Spring/Spring Boot 集成
  • 性能好,輕量級

? 缺點

  • SQL 手寫多,維護成本高
  • 不支持完整的 ORM 功能(不像 Hibernate 自動生成表結構)

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

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

相關文章

1.6-抓包技術(Burp Suite\Yakit抓包\Web、APP、小程序)

1.6-抓包技術&#xff08;Burp Suite\Yakit抓包\Web、APP、小程序&#xff09; 如果要使用抓包軟件&#xff0c;基本上第一步都是要安裝證書的。原因如下&#xff1a; 客戶端&#xff08;瀏覽器或應用&#xff09;會檢測到證書不受信任&#xff0c;并彈出 證書錯誤&#xff0…

Java 大視界 -- 基于 Java 的大數據隱私保護在金融客戶信息管理中的實踐與挑戰(178)

&#x1f496;親愛的朋友們&#xff0c;熱烈歡迎來到 青云交的博客&#xff01;能與諸位在此相逢&#xff0c;我倍感榮幸。在這飛速更迭的時代&#xff0c;我們都渴望一方心靈凈土&#xff0c;而 我的博客 正是這樣溫暖的所在。這里為你呈上趣味與實用兼具的知識&#xff0c;也…

第十屆 藍橋杯 嵌入式 省賽

一、分析 這屆的真題&#xff0c;有點像第七屆的液位檢測。 這屆的題目開始&#xff0c;貌似比賽描述的功能&#xff0c;邏輯上變得更好梳理了。一開始就把大致的功能給你說明一遍&#xff0c;不像之前都是一塊一塊的說明。 1. 基本功能 1&#xff09;測量競賽板上電位器 R…

實現usb的MTP功能

前言:最終結果根據用戶自主選擇可實現host和device功能的切換。 效果展示: 當插入usb時設備會彈窗 當用戶選擇設備模式時pc端就會出現mtp設備盤符 實現mtp設備 ubuntu架構根文件系統通過uMTP-Responder實現usb的MTP功能 添加服務 /home/flynn/firfly_rootfs/lib/system…

React-05React中props屬性(傳遞數據),propTypes校驗,類式與函數式組件props的使用

1.類式組件props基本數據讀取與解構運算符傳遞 <script type"text/babel">// 創建組件class PersonalInfo extends React.Component {render() {// 讀取props屬性 并讀取值console.log(props,this.props);return(<ul><li>姓名&#xff1a;{this.p…

PCI認證 密鑰注入 ECC算法工具 NID_secp521r1 國密算法 openssl 全套證書生成,從證書提取公私鑰數組 x,y等

步驟 1.全套證書已經生成。OK 2.找國芯要ECC加密解密簽名驗簽代碼。給的邏輯說明沒有示例代碼很難的上。 3.集成到工具 與SP聯調。 1.用openssl全套證書生成及驗證 注意&#xff1a;這里CA 簽發 KLD 證書用的是SHA256。因為芯片只支持SHA256算法,不支持SHA512。改成統一。…

藍橋杯每日刷題c++

目錄 P9240 [藍橋杯 2023 省 B] 冶煉金屬 - 洛谷 (luogu.com.cn) P8748 [藍橋杯 2021 省 B] 時間顯示 - 洛谷 (luogu.com.cn) P10900 [藍橋杯 2024 省 C] 數字詩意 - 洛谷 (luogu.com.cn) P10424 [藍橋杯 2024 省 B] 好數 - 洛谷 (luogu.com.cn) P8754 [藍橋杯 2021 省 AB2…

oracle 數據庫字段類型為NUMBER(5,2)時,并且數據庫值為0.1,為什么Java執行SQL查出來時為“.1“?

在 Oracle 數據庫中&#xff0c;當字段類型為 NUMBER(5,2) 且存儲的值為 0.1 時&#xff0c;Java 程序查詢結果可能顯示為 ".1"&#xff08;省略前導零&#xff09;&#xff0c;這是由 Oracle JDBC 驅動默認的數字格式化行為 導致的。以下是原因分析和解決方案&#…

3月AI論文精選十篇

1. Feature-Level Insights into Artificial Text Detection with Sparse Autoencoders[1] 核心貢獻&#xff1a;通過稀疏自編碼器揭示AI生成文本的檢測特征&#xff0c;提出基于特征分布的鑒別方法。研究發現&#xff0c;AI文本在稀疏編碼空間中呈現獨特的"高頻低幅"…

STM32在裸機(無RTOS)環境下,需要手動實現隊列機制來替代FreeRTOS的CAN發送接收函數

xQueueSendToBackFromISR(ecuCanRxQueue, hcan->pRxMsg, &xHigherPriorityTaskWoken)&#xff0c;xQueueReceive(mscCanRxQueue,&mscRxMsg,0)和xQueueSendToBack(mscCanTxQueue, &TxMessageTemp, 0 )這3個函數&#xff0c;在裸機下實現&#xff1a; 在裸機&…

使用PX4,gazebo,mavros為旋翼添加下視的相機(仿真采集openrealm數據集-第一步)

目錄 一.方法一&#xff08;沒成功&#xff09; 1.運行PX4 2.運行mavros通訊 3.啟動仿真世界和無人機 &#xff08;1&#xff09;單獨測試相機 &#xff08;2&#xff09;make px4_sitl gazebo啟動四旋翼iris無人機 二.方法二&#xff08;成功&#xff09; 1.通過 rosl…

7、nRF52xx藍牙學習(nrf_gpiote.c庫函數學習)

續前一篇文章。 3、nrfx_gpiote_in_event_enable void nrfx_gpiote_in_event_enable(nrfx_gpiote_pin_t pin, bool int_enable) {NRFX_ASSERT(nrf_gpio_pin_present_check(pin));NRFX_ASSERT(pin_in_use_by_gpiote(pin));if (pin_in_use_by_port(pin)){nrf_gpiote_polarity_t…

Java 實現插入排序:[通俗易懂的排序算法系列之三]

引言 大家好!歡迎繼續關注我的排序算法系列。今天,我們要學習的是另一種非常基礎且重要的排序算法——插入排序 (Insertion Sort)。 插入排序的思路非常貼近我們日常整理撲克牌的方式,理解起來相對自然。雖然它在最壞情況下的效率不高,但在某些特定場景下,它的表現甚至優…

Java的spring boot項目編譯成功啟動報錯

問題現象&#xff1a;spring boot項目&#xff0c;候刪除一些無用代碼后&#xff0c;build成功&#xff0c;啟動時報錯&#xff1a;找不到java.util.Map或者其他對象&#xff08;用Lombok注解Data&#xff09;中的字段屬性找不到等錯誤。解答&#xff1a; 常見是Lombok版本問題…

PyTorch參數管理詳解:從訪問到初始化與共享

本文通過實例代碼講解如何在PyTorch中管理神經網絡參數&#xff0c;包括參數訪問、多種初始化方法、自定義初始化以及參數綁定技術。所有代碼可直接運行&#xff0c;適合深度學習初學者進階學習。 1. 定義網絡與參數訪問 1.1 定義單隱藏層多層感知機 import torch from torch…

基于springboot+vue的課程管理系統

一、系統架構 前端&#xff1a;vue | element-ui 后端&#xff1a;springboot | mybatis-plus 環境&#xff1a;jdk1.8 | mysql8 | maven | node v16.20.2 | idea 二、代碼及數據 三、功能介紹 01. 登錄 02. 管理員-首頁 03. 管理員-系管理 04. 管理員-專業管理 05. 管…

ssh密鑰連接遠程服務器并用scp傳輸文件

ssh密鑰連接遠程服務器 私鑰的權限必須是600chmod 600 id_rsa連接時在命令中加上私鑰的地址ssh -i PATH_to_id_rsa usernameip -p port scp -P port -i PATH_to_id_rsa file usernameip:PATH

ElasticSearch遷移數據

一、查詢索引 1、查詢所有索引 curl --user elastic:123456 -XGET "http://localhost:19200/_cat/indices?v&sindex" 2、查詢索引配置 以索引名稱hello為例 curl --user elastic:123456 -XGET "http://localhost:19200/hello/_settings?pretty" 3…

【Unity】animator檢測某state動畫播放完畢方法

博主對動畫系統很不熟&#xff0c;可能使用的方法比較曲折&#xff0c;但是我確實沒找到更有效的方法了。 unity的這個animator在我看來簡直有毛病啊&#xff0c;為什么那么難以獲取某狀態動畫的信息呢&#xff1f;&#xff1f;&#xff1f; 想要知道動畫播完沒有只有用norma…

Jmeter 插件【性能測試監控搭建】

1. 安裝Plugins Manager 1.1 下載路徑&#xff1a; Install :: JMeter-Plugins.org 1.2 放在lib/ext目錄下 1.3 重啟Jmeter&#xff0c;會在菜單-選項下多一個 Plugins Manager菜單&#xff0c;打開即可對插件進行安裝、升級。 2. 客戶端(Jmeter端) 2.1 安裝plugins manager…