Spring快速整合Mybatis

MyBatis是一個優秀的持久層框架,Spring則是廣泛使用的Java應用框架。可以將兩者整合可以充分發揮各自的優勢。

1、Spring整合MyBatis的基本配置

添加依賴:

<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.10</version>
</dependency>
<!-- Spring JDBC支持 -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.10</version>
</dependency>
<!-- MyBatis核心 -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version>
</dependency>
<!-- MyBatis-Spring整合包 -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version>
</dependency>
<!-- 數據庫驅動 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version>
</dependency>

Spring配置文件:
創建Spring配置文件applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置數據源 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis_db?useSSL=false&amp;serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="password"/></bean><!-- 配置SqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><!-- 指定MyBatis配置文件 --><property name="configLocation" value="classpath:mybatis-config.xml"/><!-- 指定mapper.xml文件位置 --><property name="mapperLocations" value="classpath:mapper/*.xml"/></bean><!-- 配置Mapper掃描器 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.example.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean><!-- 開啟注解掃描 --><context:component-scan base-package="com.example"/>
</beans>

MyBatis配置文件:
創建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><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings><typeAliases><package name="com.example.entity"/></typeAliases>
</configuration>

2、基本的CRUD操作

創建實體類:

package com.example.entity;
public class User {private Long id;private String username;private String password;private String email;// 省略getter和setter方法// 省略toString方法
}

創建Mapper接口:

package com.example.mapper;
import com.example.entity.User;
import java.util.List;
public interface UserMapper {int insert(User user);int update(User user);int deleteById(Long id);User selectById(Long id);List<User> selectAll();
}

創建Mapper XML文件:
在resources/mapper目錄下創建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"><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO user(username, password, email)VALUES(#{username}, #{password}, #{email})</insert><update id="update" parameterType="User">UPDATE userSET username=#{username}, password=#{password}, email=#{email}WHERE id=#{id}</update><delete id="deleteById" parameterType="long">DELETE FROM user WHERE id=#{id}</delete><select id="selectById" parameterType="long" resultType="User">SELECT * FROM user WHERE id=#{id}</select><select id="selectAll" resultType="User">SELECT * FROM user</select>
</mapper>

創建Service層:

package com.example.service;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public int addUser(User user) {return userMapper.insert(user);}public int modifyUser(User user) {return userMapper.update(user);}public int removeUser(Long id) {return userMapper.deleteById(id);}public User getUserById(Long id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.selectAll();}
}

測試類:

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Application {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService = context.getBean(UserService.class);// 添加用戶User user = new User();user.setUsername("testUser");user.setPassword("123456");user.setEmail("test@example.com");userService.addUser(user);System.out.println("添加用戶成功,ID: " + user.getId());// 查詢用戶User dbUser = userService.getUserById(user.getId());System.out.println("查詢用戶: " + dbUser);// 更新用戶dbUser.setEmail("newemail@example.com");userService.modifyUser(dbUser);System.out.println("更新用戶成功");// 查詢所有用戶List<User> users = userService.getAllUsers();System.out.println("所有用戶:");users.forEach(System.out::println);// 刪除用戶userService.removeUser(user.getId());System.out.println("刪除用戶成功");}
}

3、動態SQL和分頁查詢

擴展Mapper接口:
// 在UserMapper接口中添加

List<User> selectByCondition(@Param("username") String username, @Param("email") String email);List<User> selectByPage(@Param("offset") int offset, @Param("pageSize") int pageSize);

擴展Mapper XML:

<!--UserMapper.xml中添加 -->
<select id="selectByCondition" resultType="User">SELECT * FROM user<where><if test="username != null and username != ''">AND username LIKE CONCAT('%', #{username}, '%')</if><if test="email != null and email != ''">AND email LIKE CONCAT('%', #{email}, '%')</if></where>
</select>
<select id="selectByPage" resultType="User">SELECT * FROM user LIMIT #{offset}, #{pageSize}
</select>

擴展Service:
// 在UserService中添加

public List<User> getUsersByCondition(String username, String email) {return userMapper.selectByCondition(username, email);
}
public List<User> getUsersByPage(int pageNum, int pageSize) {int offset = (pageNum - 1) * pageSize;return userMapper.selectByPage(offset, pageSize);
}

測試動態SQL和分頁:
// 在Application的main方法中添加測試代碼

System.out.println("條件查詢:");
List<User> conditionUsers = userService.getUsersByCondition("test", null);
conditionUsers.forEach(System.out::println);
System.out.println("分頁查詢(第1頁,每頁2條):");
List<User> pageUsers = userService.getUsersByPage(1, 2);
pageUsers.forEach(System.out::println);

4、事務管理

修改Spring配置

在applicationContext.xml中添加事務配置:
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/>
</bean>
<!-- 開啟注解驅動的事務管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

創建事務性Service方法:

@Transactional
public void transferEmail(Long fromId, Long toId, String newEmail) {User fromUser = userMapper.selectById(fromId);User toUser = userMapper.selectById(toId);if(fromUser == null || toUser == null) {throw new RuntimeException("用戶不存在");}// 將fromUser的email設置為newEmailfromUser.setEmail(newEmail);userMapper.update(fromUser);// 模擬異常if(newEmail.contains("error")) {throw new RuntimeException("測試事務回滾");}// 將toUser的email也設置為newEmailtoUser.setEmail(newEmail);userMapper.update(toUser);
}

測試事務:

try {userService.transferEmail(1L, 2L, "transaction@example.com");System.out.println("事務操作成功");
} catch (Exception e) {System.out.println("事務操作失敗: " + e.getMessage());
}
try {userService.transferEmail(1L, 2L, "error@example.com");
} catch (Exception e) {System.out.println("事務回滾測試: " + e.getMessage());
}

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

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

相關文章

基于深度學習的語音識別:從音頻信號到文本轉錄

前言 語音識別&#xff08;Automatic Speech Recognition, ASR&#xff09;是人工智能領域中一個極具挑戰性和應用前景的研究方向。它通過將語音信號轉換為文本&#xff0c;為人們提供了更加自然和便捷的人機交互方式。近年來&#xff0c;深度學習技術在語音識別領域取得了顯著…

本地部署Nacos開源服務平臺,并簡單操作實現外部訪問,Windows 版本

Nacos 是一款阿里開源的動態服務發現、配置、管理平臺&#xff0c;擁有易于集成、高可用與可擴展等特點。它提供了動態服務注冊和發現能力&#xff0c;使得服務自動注冊到服務器并且消費真能夠發現提供者。本文將詳細介紹如何在本地安裝 Nacos &#xff0c;以及結合nat123端口映…

數據結構:反轉字符串(Reversing a String)

目錄 方法一&#xff1a;雙指針法 方法二&#xff1a;輔助數組 方法對比總結&#xff1a; 問題定義 給定一個字符串&#xff0c;例如&#xff1a; char str[] "hello";我們的目標是把它反轉成&#xff1a; "olleh"&#x1f4cc; 輸入特點&#xff…

Redis Copy-on-Write機制:

Copy-on-Write機制&#xff1a; 父子進程共享內存頁 當父進程修改數據時&#xff0c;內核會復制被修改的頁 這可能導致內存使用量暫時增加 通俗的話描述一下可以用一個生活中的例子來通俗解釋 Copy-on-Write&#xff08;寫時復制&#xff09; 機制&#xff1a;&#x1f4d6; 比…

iOS加固工具有哪些?從零源碼到深度混淆的全景解讀

在iOS安全加固領域&#xff0c;不同項目類型對保護需求有著本質差異&#xff1a;“我有源碼”與“我只有IPA”兩條路徑決定了你該用什么工具。本文將從 無需源碼處理整個IPA包 到 源碼級編譯期混淆&#xff0c;分層探討主流工具如何發揮價值&#xff0c;并附上適配方案建議。工…

Composer 可以通過指定 PHP 版本運行

是的&#xff0c;Composer 可以通過指定 PHP 版本運行&#xff0c;尤其是在服務器上有多個 PHP 版本時&#xff08;如 PHP 7.x 和 PHP 8.x&#xff09;。以下是幾種常見方法&#xff1a;方法 1&#xff1a;使用 php 命令指定版本 Composer 依賴系統中的 php 命令&#xff0c;因…

vscode文件顏色,只顯示自己更改的文件顏色

這個主要是因為你github git下來以后&#xff0c;用vscode打開會默認顯示更改了&#xff0c;你只要在這里先手動取消更改就行了&#xff0c;注意不要把你自己更改的取消了

記錄我coding印象比較深刻的BUG

4778&#xff1a;我的BUG噩夢問題描述&#xff1a;DAB播放中關ACC掉電后開ACC&#xff0c;手動切到FM/AM(有時第一次切換出現問題/有時第二次切換出現問題)&#xff0c;FM/AM不記憶關ACC前電臺或者FM/AM關ACC掉電后開ACC&#xff0c;手動切到DAB再回到FM/AM&#xff0c;FM/AM不…

Kubernetes集群中Istio mTLS握手失敗問題排查與解決方案

Kubernetes集群中Istio mTLS握手失敗問題排查與解決方案 在微服務架構中&#xff0c;Istio 提供了基于 Envoy 的服務網格能力&#xff0c;其中 mTLS&#xff08;雙向 TLS&#xff09;是確保服務間通信安全的重要機制。但在生產環境中&#xff0c;開發者常常會遇到 mTLS 握手失敗…

antd+react+可輸入的下拉選擇組件

該組件是一個可輸入的下拉選擇組件&#xff0c;支持從預設選項中選擇或手動輸入自定義值。組件基于 React 和 Ant Design 實現&#xff0c;具有良好的交互體驗和靈活的配置選項。 &#x1f9e0; 核心邏輯分析 1. 狀態管理 const [isInput, setIsInput] useState(false); con…

React 面試題庫

openAI React 面試題庫 以下題庫按模塊分類&#xff08;React 架構與運行機制、核心 API、Diff 算法與事件機制、Fiber 架構與調度、并發模式與過渡、生命周期及新版生命周期對照、綜合源碼題、擴展專題、React 與 Vue 對比&#xff09;&#xff0c;并按難度&#xff08;初級…

查看兩個tv and 手機模擬器的ip

要查看 Android 模擬器 的 IP 地址&#xff0c;你可以使用 ADB shell 命令來獲取。下面是詳細步驟&#xff1a;步驟 1&#xff1a;查看已連接的模擬器首先&#xff0c;確保你連接的模擬器已經啟動并且連接到 ADB。你可以運行以下命令來查看已連接的設備&#xff1a;adb devices…

從零到一:用C語言構建貪吃蛇(一)- 基礎框架與數據結構

資料合集下載鏈接: ??https://pan.quark.cn/s/472bbdfcd014? 第一步:繪制游戲世界 - 定義地圖邊界 任何游戲都需要一個舞臺。在貪吃蛇中,這個舞臺就是一個有明確邊界的矩形地圖。 1. 確定尺寸 根據筆記,我們首先要確定地圖的尺寸。使用宏定義(??#define??)是…

AWS RDS 排查性能問題

AWS RDS 排查數據庫問題 1.查看當前橫在執行的SQL select id,user,time,left(info,100) from information_schema.processlist where time>0 and info is not null order by time desc ;2.AWS RDS 查看性能詳情查看 Top SQL&#xff0c;AAS最高的幾個sql&#xff0c;然后看這…

Baumer工業相機堡盟工業相機如何通過YoloV8深度學習模型實現持械檢測(C#代碼,UI界面版)

Baumer工業相機堡盟工業相機如何通過YoloV8深度學習模型實現持械檢測&#xff08;C#代碼&#xff0c;UI界面版&#xff09;工業相機使用YoloV8模型實現持械檢測工業相機通過YoloV8模型實現持械檢測的技術背景在相機SDK中獲取圖像轉換圖像的代碼分析工業相機圖像轉換Bitmap圖像格…

在 WPF 啟動界面中心加載 GIF 動圖

在 WPF 啟動界面中心加載 GIF 動圖 在 WPF 啟動界面中心加載 GIF 動圖可以通過多種方式實現。下面我將提供一個完整的解決方案&#xff0c;包括使用第三方庫和純 WPF 實現兩種方法。 方法一&#xff1a;使用 WpfAnimatedGif 庫&#xff08;推薦&#xff09; 這是最簡單可靠的方…

Vue前端路由從入門到精通

目錄 第1章:路由的本質與Vue Router的魅力 1.1 什么是前端路由? 1.2 為什么選擇Vue Router? 1.3 快速上手:安裝與基本配置 1.4 一個小實踐:動態歡迎頁 第2章:路由配置的進階玩法 2.1 命名路由:給路由取個名字 2.2 動態路由的深度挖掘 2.3 嵌套路由:頁面中的頁面…

【Python】SQLAlchemy實現upsert

文章目錄? 通用思路1. 使用 merge() 方法&#xff08;適用于簡單場景&#xff09;2. 使用數據庫特定的 UPSERT 功能&#xff08;推薦用于性能和并發安全&#xff09;&#x1f7e2; PostgreSQL: 使用 on_conflict_do_update&#x1f7e1; MySQL: 使用 ON DUPLICATE KEY UPDATE&…

快速入門SwiftUI

SwiftUI的入門難度稍微有點高&#xff0c;但對于比較熟悉Swift的UIKit老手來說陣痛期大概1周以內&#xff0c;兩周內能達到UIkit的開發效率&#xff0c;個人總結快速入門路徑如下&#xff1a; 第一步 周期&#xff1a;1天 操作&#xff1a;閱讀蘋果官方demo 目的&#xff1a;…

【n8n教程筆記——工作流Workflow】文本課程(第一階段)——1、導航編輯器界面(Navigating the editor UI)介紹

https://docs.n8n.io/courses/ 文章目錄Navigating the Editor UIGetting startedEditor UI settingsLeft-side panelTop barCanvasNodesFinding nodesAdding nodesNode buttonsSummaryNavigating the Editor UI In this lesson you will learn how to navigate the Editor UI…