Spring6 對 集成MyBatis 開發運用(附有詳細的操作步驟)

詳細實現操作步驟

具體實現內容:我們運用 Spring6 和 MyBatis 實現一個轉賬操作(該轉賬操作,進行一個事務上的控制,運用 MyBatis 執行 SQL 語句)。

  1. 第一步:準備數據庫表

  • 使用t_act表(賬戶表)

連接數據庫的工具有很多,這里我們可以使用IDEA工具自帶的 DataBase 插件。可以根據下圖提示自行配置:

一般是在 IDEA 的左邊,DataBase

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

如下是 t_act 的表結構

在這里插入圖片描述

如下是 t_act 的表數據內容:

在這里插入圖片描述

  1. 第二步:IDEA中創建一個模塊,并引入依賴

  • spring-context

    spring-jdbc

    mysql驅動

    mybatis

    mybatis-spring:mybatis提供的與spring框架集成的依賴

    德魯伊連接池

    junit

我們先在pom.xml?配置文件當中導入相關的?jar?包信息:

在這里插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.rainbowsea</groupId><artifactId>spring6-016-mybaits</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><!--倉庫--><repositories><!--spring里程碑版本的倉庫--><repository><id>repository.spring.milestone</id><name>Spring Milestone Repository</name><url>https://repo.spring.io/milestone</url></repository></repositories><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.0-M2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.0-M2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.13</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies></project>

  1. 第三步:基于三層架構實現,所以提前創建好所有的包

  • com.powernode.bank.mapper

    com.powernode.bank.service

    com.powernode.bank.service.impl

    com.powernode.bank.pojo

在這里插入圖片描述

在這里插入圖片描述

  1. 第四步:編寫pojo

  • Account,屬性私有化,提供公開的setter getter和toString。

在這里插入圖片描述

  1. 第五步:編寫mapper接口

  • AccountMapper接口,定義方法

在這里插入圖片描述

package com.rainbowsea.bank.mapper;import com.rainbowsea.bank.pojo.Account;import java.util.List;// 該接口的實現類不需要寫,是mybatis通過動態代理機制生成的實現類
public interface AccountMapper {// 這就是DAO,只要編寫CRUD方法即可/*** 新增賬戶* @param account* @return*/int insert(Account account);/*** 根據賬戶刪除賬戶* @param actno* @return*/int deleteByActno(String actno);/*** 根據賬戶更新* @param account* @return*/int update(Account account);/*** 根據賬戶查詢賬戶* @param actno* @return*/Account selectByActno(String actno);/*** 查詢所有的賬戶* @return*/List<Account> selectAll();}

  1. 第六步:編寫mapper配置文件

  • 在配置文件中配置命名空間,以及每一個方法對應的sql。

一定要注意,按照下圖提示創建這個目錄。注意是 斜杠(因為是創建目錄) 不是點兒。在resources目錄下新建。并且要和Mapper接口包對應上。因為只有這樣,MyBatis 才會進行動態代理這個接口。

同時:如果接口叫做AccountMapper,配置文件必須是 AccountMapper.xml,名稱要保持一致。

總結兩點:就是路徑位置要保持一致,對應的名稱也要保持一致。后綴名不同。

在這里插入圖片描述

在這里插入圖片描述

同時在?AccountMapper.xml?當中編寫 SQL 語句內容。

在這里插入圖片描述

<?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.rainbowsea.bank.mapper.AccountMapper"><insert id="insert">insert into t_act(actno,balance) values(#{actno}, #{balance})</insert><delete id="deleteByActno">delete from t_act where actno = #{actno}</delete><update id="update">update t_act set balance = #{balance} where actno = #{actno}</update><select id="selectByActno" resultType="Account">select * from t_act where actno = #{actno}</select><select id="selectAll" resultType="Account">select * from t_act</select>
</mapper>

  1. 第七步:編寫service接口和service接口實現類

  • AccountService

    AccountServiceImpl

編寫 AccountService 業務接口,定義約束,規范,進行一個業務上的轉賬操作。

在這里插入圖片描述

package com.rainbowsea.bank.service;import com.rainbowsea.bank.pojo.Account;
import org.springframework.transaction.annotation.Transactional;import java.util.List;public interface AccountService {/*** 開戶* @param account* @return*/int save(Account account);/*** 根據賬號銷戶* @param actno* @return*/int deleteByActno(String actno);/*** 修改賬戶* @param act* @return*/int update(Account act);/*** 根據賬號獲取賬戶* @param actno* @return*/Account getByActno(String actno);/*** 獲取所有賬戶* @return*/List<Account> getAll();/*** 轉賬* @param fromActno* @param toActno* @param money*/void transfer(String fromActno, String toActno, double money);
}

注意:要將編寫的service實現類納入IoC容器管理,同時注意需要開啟事務@Transactional

在這里插入圖片描述

在這里插入圖片描述

package com.rainbowsea.bank.service.impl;import com.rainbowsea.bank.mapper.AccountMapper;
import com.rainbowsea.bank.pojo.Account;
import com.rainbowsea.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service(value = "accountServiceImpl")
@Transactional  // 放在類中,下面的類中的所有方法都開啟了事務
public class AccountServiceImpl implements AccountService {// Could not find bean with name 'org.mybatis.spring.SqlSessionFactoryBean#0@Autowired // 非簡單類型自動裝配private AccountMapper accountMapper;@Overridepublic int save(Account account) {return accountMapper.insert(account);}@Overridepublic int deleteByActno(String actno) {return accountMapper.deleteByActno(actno);}@Overridepublic int update(Account act) {return accountMapper.update(act);}@Overridepublic Account getByActno(String actno) {return accountMapper.selectByActno(actno);}@Overridepublic List<Account> getAll() {return accountMapper.selectAll();}@Overridepublic void transfer(String fromActno, String toActno, double money) {Account fromAct = accountMapper.selectByActno(fromActno);if(fromAct.getBalance() < money) {throw new RuntimeException("余額不足");}Account toAct = accountMapper.selectByActno(toActno);//模擬異常/*  String s = null;s.toString();
*/// 內存上修改fromAct.setBalance(fromAct.getBalance() - money);toAct.setBalance(toAct.getBalance() + money);// 數據庫上修改數據內容int count = accountMapper.update(fromAct);count += accountMapper.update(toAct);if(count != 2) {throw new RuntimeException("轉賬失敗");}}
}

  1. 第八步:在 resources 的根路徑下,編寫jdbc.properties配置文件

  • 數據庫連接池相關信息,賬號,密碼,同時注意要加上?jdbc, 同時注意不要加任何的空格,同時是 放在類的根路徑(resources )下

在這里插入圖片描述

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring6
jdbc.username=root
jdbc.password=MySQL123

  1. 第九步:編寫mybatis-config.xml配置文件

  • 該文件可以沒有,大部分的配置可以轉移到spring配置文件中。

    如果遇到mybatis相關的系統級配置,還是需要這個文件。

    放在類的根路徑(resources )下,只開啟日志,其他配置到spring.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>
<!--    幫助我們打印mybatis的日志信息。sql語句等--><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings></configuration>

  1. 第十步:編寫spring.xml配置文件

  • 組件掃描

    引入外部的屬性文件

    數據源

    SqlSessionFactoryBean配置

    注入mybatis核心配置文件路徑

    指定別名包

    注入數據源

    Mapper掃描配置器

    指定掃描的包

    事務管理器DataSourceTransactionManager

    注入數據源

    啟用事務注解

    注入事務管理器

  • 同樣,我們還是將其防止到 類的根路徑下(resources )

注意:當你在spring.xml文件中直接寫標簽內容時,IDEA會自動給你添加命名空間

在這里插入圖片描述

<?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"xmlns:tx="http://www.springframework.org/schema/tx"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.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--    組件掃描,--><context:component-scan base-package="com.rainbowsea.bank"></context:component-scan><!--    引入外部的屬性配置文件--><context:property-placeholder location="jdbc.properties"></context:property-placeholder><!--    數據源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean><!--    配置SqlSessionFactoryBean  "org.mybatis.spring.SqlSessionFactoryBean"--><bean class="org.mybatis.spring.SqlSessionFactoryBean"><!--        注入數據源--><property name="dataSource" ref="dataSource"></property><!--        指定mybatis 核心配置文件--><property name="configLocation" value="mybatis-config.xml"></property><!--        指定別名--><property name="typeAliasesPackage" value="com.rainbowsea.bank.pojo"></property></bean><!--    Mapper 掃描配置器,主要掃描Mapper 接口,生成代理類--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.rainbowsea.bank.mapper"></property></bean><!--    事務管理器--><bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--        配置數據源--><property name="dataSource" ref="dataSource"></property></bean><!--    啟用事務注解,事務管理器--><tx:annotation-driven transaction-manager="txManger"></tx:annotation-driven>
</beans>

  1. 第十一步:編寫測試程序,并添加事務,進行測試

在這里插入圖片描述

在這里插入圖片描述

package com.rainbowsea.spring6.test;import com.rainbowsea.bank.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringMybatisTest {@Testpublic void testSpringMybatis() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");// AccountService.class 左右兩邊保持一致性AccountService accountService = applicationContext.getBean("accountServiceImpl", AccountService.class);try {accountService.transfer("act-001","act-002",10000);System.out.println("轉賬成功");} catch (Exception e) {throw new RuntimeException(e);}}
}

沒有異常,看是否能轉賬成功

在這里插入圖片描述

模擬異常,看是否,能夠進行正常的事務回滾

在這里插入圖片描述

運行測試:

在這里插入圖片描述

在這里插入圖片描述


4. Spring配置文件的 import,導入外部xml 配置

如果 spring 配置文件有多個,可以在 spring 的核心配置文件中使用?import?進行引入,我們可以將組件掃描單獨定義到一個配置文件中,如下:我們將一個《組件掃描》,定義到一個單獨的名為common.xml的配置文件當中去,并導入,引入到 spring 的配置文件當中使用。如下:

在這里插入圖片描述

使用<import>?標簽進行一個導入

在這里插入圖片描述

<!--    在Spring 的核心配置文件中引入其他的子 spring 配置文件--><import resource="common.xml"></import>

把模擬異常去了,測試,是否能夠轉賬成功。如下:

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

注意:在實際開發中,service 單獨配置到一個文件中,dao單獨配置到一個文件中,然后在核心配置文件中引入,養成好習慣。

5. 總結:

  1. Spring6 對集成MyBatis 開發:這里總的來說是十步,完成的。

  2. 一定要注意,按照下圖提示創建這個目錄。注意是 斜杠(因為是創建目錄) 不是點兒。在resources目錄下新建。并且要和Mapper接口包對應上。因為只有這樣,MyBatis 才會進行動態代理這個接口。

    同時:如果接口叫做AccountMapper,配置文件必須是 AccountMapper.xml,名稱要保持一致。

    總結兩點:就是路徑位置要保持一致,對應的名稱也要保持一致。后綴名不同。

  3. Spring 當中使用<import>?標簽導入外部xml 配置。

文章轉載自:Rainbow-Sea

原文鏈接:https://www.cnblogs.com/TheMagicalRainbowSea/p/18211700

體驗地址:引邁 - JNPF快速開發平臺_低代碼開發平臺_零代碼開發平臺_流程設計器_表單引擎_工作流引擎_軟件架構

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

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

相關文章

三個有意思的鏈表面試題的完成

上一篇博客我們已經完成了鏈表的所有內容&#xff0c;那么這一篇博客我們來看一下三個特別有意思的鏈表題目。 **第一個題目如下&#xff1a;**相信不少朋友看到這題目就已經暈了&#xff0c;那就簡單說明下這個題目&#xff0c;題目就是創建一個鏈表&#xff0c;其中每個節點…

深入探索Java中的流式編程:優雅地處理集合數據

Java流式編程&#xff08;Stream API&#xff09;是Java 8引入的一項重要特性&#xff0c;它為處理集合數據提供了一種更為優雅和函數式的方式。通過流式操作&#xff0c;開發者可以以更簡潔、更直觀的方式處理數據&#xff0c;從而提高代碼的可讀性和可維護性。本文將深入探討…

Android14 - 繪制系統 - 概覽

從Android 12開始&#xff0c;Android的繪制系統有結構性變化&#xff0c; 在繪制的生產消費者模式中&#xff0c;新增BLASTBufferQueue&#xff0c;客戶端進程自行進行queue的生產和消費&#xff0c;隨后通過Transation提交到SurfaceFlinger&#xff0c;如此可以使得各進程將緩…

【vue3+elementuiplus】el-select下拉框會自動觸發校驗規則

場景&#xff1a;編輯彈框省份字段下拉框必填&#xff0c;觸發方式change&#xff0c;有值第一次打開不會觸發校驗提示&#xff0c;關閉彈框再次打開觸發必填校驗提示&#xff0c;但是該字段有值 問題的原因是&#xff1a;在關閉彈層事件中&#xff0c;我做了resetfileds&…

SpringBoot + MybatisPlus

SpringBoot MybatisPlus 整合記錄 1. 硬件軟件基本信息2. 相關鏈接3. 通過idea快速生成一個Springboot項目4. 啟動報錯問題解決問題一&#xff1a;Springboot啟動的時候報錯提示 “沒有符合條件的Bean關于Mapper類型”問題二&#xff1a;啟動的時候提示需要一個Bean&#xff0…

電磁仿真--CST網格介紹

1. 簡介 網格會影響仿真的準確性和速度&#xff0c;花時間理解網格化過程是很重要的。 CST 中可用的數值方法包括FIT、TLM、FEM、MoM&#xff0c;使用不同類型的網格&#xff1a; FIT和TLM&#xff1a;六面體 FEM&#xff1a;四面體、平面 MoM&#xff1a;表面 CFD&#…

深入理解與防御跨站腳本攻擊(XSS):從搭建實驗環境到實戰演練的全面教程

跨站腳本攻擊&#xff08;XSS&#xff09;是一種常見的網絡攻擊手段&#xff0c;它允許攻擊者在受害者的瀏覽器中執行惡意腳本。以下是一個XSS攻擊的實操教程&#xff0c;包括搭建實驗環境、編寫測試程序代碼、挖掘和攻擊XSS漏洞的步驟。 搭建實驗環境 1. 安裝DVWA&#xff…

【408真題】2009-16

“接”是針對題目進行必要的分析&#xff0c;比較簡略&#xff1b; “化”是對題目中所涉及到的知識點進行詳細解釋&#xff1b; “發”是對此題型的解題套路總結&#xff0c;并結合歷年真題或者典型例題進行運用。 涉及到的知識全部來源于王道各科教材&#xff08;2025版&…

推薦一個快速開發接私活神器

文章目錄 前言一、項目介紹二、項目地址三、功能介紹四、頁面顯示登錄頁面菜單管理圖表展示定時任務管理用戶管理代碼生成 五、視頻講解總結 前言 大家好&#xff01;我是智航云科技&#xff0c;今天為大家分享一個快速開發接私活神器。 一、項目介紹 人人開源是一個提供多種…

SCSS配置教程

SCSS&#xff08;Sassy CSS&#xff09;是 Sass&#xff08;Syntactically Awesome Stylesheets&#xff09;的一種語法&#xff0c;它是一種 CSS 預處理器&#xff0c;允許你使用變量、嵌套規則、混合&#xff08;mixin&#xff09;、函數等高級功能來編寫 CSS&#xff0c;從而…

Golang | Leetcode Golang題解之第112題路徑總和

題目&#xff1a; 題解&#xff1a; func hasPathSum(root *TreeNode, sum int) bool {if root nil {return false}if root.Left nil && root.Right nil {return sum root.Val}return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - roo…

C++常見知識點總結

常見字符 * 注釋&#xff1a;/* 這是一個注釋*/乘法&#xff1a;a * b取值運算符&#xff1a;*指針變量&#xff0c;int a 4&#xff0c;*a &#xff1f;&#xff1f;&#xff1f;&#xff1f;指針變量&#xff1a;數據類型 *變量名&#xff0c; int *no &bh&#xff0…

SAP揭秘者-怎么執行生產訂單ATP檢查及其注意點

文章摘要&#xff1a; 上篇文章給大家介紹生產訂單ATP檢查的相關后臺配置&#xff0c;大家可以按照配置步驟去進行配置&#xff0c;配置完之后&#xff0c;我們接下來就是要執行ATP檢查。本篇文章具體給大家介紹怎么來執行生產 訂單ATP檢查及其注意點。 執行生產訂單ATP檢查的…

Qt for android 獲取USB設備列表(二)JNI方式 獲取

簡介 基于上篇 [Qt for android 獲取USB設備列表&#xff08;一&#xff09;Java方式 獲取]&#xff0c; 這篇就純粹多了&#xff0c; 直接將上篇代碼轉換成JNI方式即可。即所有的設備連接與上篇一致。 (https://listentome.blog.csdn.net/article/details/139205850) 關鍵代碼…

Android卡頓丟幀低內存與adb shell內存狀態

Android卡頓丟幀低內存與adb shell內存狀態 卡頓丟幀除了CPU/GPU層面&#xff0c;另外&#xff0c;也需要特別注意整機低內存情況。kswapd0 是一個內核工作線程&#xff0c;內存不足時會被喚醒&#xff0c;做內存回收工作。 當內存頻繁在低水位的時候&#xff0c;kswapd0 會被頻…

webgl three 項目常用操作

分組 const group1 new THREE.Group(); //所有高層樓的父對象group1.name "高層";for (let i 0; i < 5; i) {const geometry new THREE.BoxGeometry(20, 60, 10);const material new THREE.MeshLambertMaterial({color: 0x00ffff});const mesh new THREE.Me…

Linux基礎(六):Linux 系統上 C 程序的編譯與調試

本篇博客詳細分析&#xff0c;Linux平臺上C程序的編譯過程與調試方法&#xff0c;這也是我們后續程序開發的基礎。 目錄 一、第一個hello world程序 1.1 創建.c文件 1.2 編譯鏈接 運行可執行程序 二、編譯鏈接過程 2.1 預編譯階段 2.2 編譯階段 2.3 匯編階段 2.4 鏈…

一千題,No.0025(Chess For Three)

描述 Three friends gathered to play a few games of chess together. In every game, two of them play against each other. The winner gets 2 points while the loser gets 0, and in case of a draw, both players get 1 point each. Note that the same pair of playe…

【MySQL精通之路】SQL語句(3)-鎖和事務語句

目錄 1.START TRANSACTION、COMMIT和ROLLBACK語句 2.無法回滾的語句 3.導致隱含COMMIT的語句 4.SAVEPOINT、ROLLBACK TO SAVEPOINT和RELEASE SAVEPOINT語句 5.LOCK INSTANCE FOR BACKUP和UNLOCK INSTANCE語句 6.LOCK TABLE和UNLOCK TABLES語句 6.1 表鎖獲取 6.2 表鎖釋放…

qemu+gdb調試linux內核

打開CONFIG_DEBUG_INFO,編譯內核 通過圖形菜單配置該宏,執行make menuconfig。 kernel hacking —> compile-time checks and compiler options —> compile the kernel with debug info 驗證是否打開成功,grep -nr “CONFIG_DEBUG_INFO” .config。 打開成功,然后…