国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring事務(wù)簡介及相關(guān)案例

這篇具有很好參考價值的文章主要介紹了Spring事務(wù)簡介及相關(guān)案例。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

目錄

?

一、事務(wù)簡介

二、準(zhǔn)備數(shù)據(jù)庫

三、創(chuàng)建maven項目,引入依賴和完成相關(guān)配置

1. pom.xml文件

2. 創(chuàng)建配置文件

四、編寫Java代碼

1. Account實體類

2. AccountDao接口

3. AccountService業(yè)務(wù)類?

五、測試

1. 測試方法

2. 測試結(jié)果?編輯

往期專欄&文章相關(guān)導(dǎo)讀?

1. Maven系列專欄文章

2. Mybatis系列專欄文章

3. Spring系列專欄文章?


一、事務(wù)簡介

????????事務(wù)(Transaction),一般是指要做的或所做的事情。在計算機術(shù)語中是指訪問并可能更新數(shù)據(jù)庫中各種數(shù)據(jù)項的一個程序執(zhí)行單元(unit)。事務(wù)通常由高級數(shù)據(jù)庫操縱語言或編程語言(如SQL,C++或Java)書寫的用戶程序的執(zhí)行所引起,并用形如begin transactionend transaction語句(或函數(shù)調(diào)用)來界定。事務(wù)由事務(wù)開始(begin transaction)和事務(wù)結(jié)束(end transaction)之間執(zhí)行的全體操作組成。

????????事務(wù):不可分割的原子操作。即一系列的操作要么同時成功,要么同時失敗。

????????開發(fā)過程中,事務(wù)管理一般在service層,service層中可能會操作多次數(shù)據(jù)庫,這些操作是不可分割的。否則當(dāng)程序報錯時,可能會造成數(shù)據(jù)異常。
????????如:張三給李四轉(zhuǎn)賬時,需要兩次操作數(shù)據(jù)庫:張三存款減少、李四存款增加。如果這兩次數(shù)據(jù)庫操作間出現(xiàn)異常,則會造成數(shù)據(jù)錯誤。

二、準(zhǔn)備數(shù)據(jù)庫

????????讀者把下面代碼段復(fù)制粘貼到文本,然后把后綴名改為sql,就是sql文件了,然后打開數(shù)據(jù)庫運行數(shù)據(jù)庫腳本即可。這里就一個表,字段有id,用戶名,余額。

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `balance` double NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '張三', 1000);
INSERT INTO `account` VALUES (2, '李四', 1000);

SET FOREIGN_KEY_CHECKS = 1;

三、創(chuàng)建maven項目,引入依賴和完成相關(guān)配置

????????這里我們需要引入的依賴有:mysql驅(qū)動包,druid連接池,spring依賴,MyBatis與Spring的整合包,該包可以讓Spring創(chuàng)建MyBatis的對象,junit測試,spring整合測試模塊依賴的依賴。

1. pom.xml文件

<?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.example</groupId>
    <artifactId>spring_transfer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <!--  mybatis  -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!--  mysql驅(qū)動包  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <!--  druid連接池  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.13</version>
        </dependency>

        <!-- MyBatis與Spring的整合包,該包可以讓Spring創(chuàng)建MyBatis的對象 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.13</version>
        </dependency>
        <!--  AspectJ    -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
        <!-- junit,如果Spring5整合junit,則junit版本至少在4.12以上 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- spring整合測試模塊 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

2. 創(chuàng)建配置文件

????????配置文件主要用于數(shù)據(jù)庫的連接,還有bean對象的建立,如下就是applicationContext.xml文件的內(nèi)容

<?xml version="1.0" encoding="UTF-8"?>

<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:http="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 包掃描 -->
    <context:component-scan base-package="com.example"/>
    <!-- 創(chuàng)建druid數(shù)據(jù)源對象 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///spring"/>
        <property name="username" value="root"/>
        <property name="password" value="666666"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>

    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.dao"/>
    </bean>

</beans>

四、編寫Java代碼

這里同樣是編寫賬戶的實體類即可,然后還要寫一個Dao接口,業(yè)務(wù)層。

1. Account實體類

package com.example.pojo;

public class Account {

    // 賬號
    private int id;
    // 用戶名
    private String username;
    // 余額
    private double balance;

    public Account() {
    }

    public Account(int id, String username, double balance) {
        this.id = id;
        this.username = username;
        this.balance = balance;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account[ " +
                "id=" + id +
                ", username='" + username + '\'' +
                ", balance=" + balance +
                " ]";
    }
}

2. AccountDao接口

package com.example.dao;

import com.example.pojo.Account;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

@Repository
public interface AccountDao {

    // 根據(jù)id查找用戶
    @Select("select * from account where id=#{id}")
    Account findById(int id);

    // 修改用戶
    @Update("update account set balance = #{balance} where id = #{id}")
    void update(Account account);
}

3. AccountService業(yè)務(wù)類?

package com.example.service;

import com.example.dao.AccountDao;
import com.example.pojo.Account;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    /**
     *
     * @param id1 轉(zhuǎn)出人id
     * @param id2 轉(zhuǎn)入人id
     * @param price 金額
     */
    // 作用方法上時,該方法都將具有該類型事務(wù)的事務(wù)屬性
    public void transfer(int id1,int id2, double price){

        // 轉(zhuǎn)出人減少余額
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance() - price);
        accountDao.update(account1);

        // 模擬程序出錯
        int i = 1 / 0;

        // 轉(zhuǎn)入人增加余額
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance() + price);
        accountDao.update(account2);
    }

}

五、測試

1. 測試方法

import com.example.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer(1,2,500);
    }
}

2. 測試結(jié)果

?OK,可以看到這里程序是出現(xiàn)異常中斷了的。?現(xiàn)在觀看數(shù)據(jù)庫里面的情況是怎么樣的。

Spring事務(wù)簡介及相關(guān)案例

????????此時沒有事務(wù)管理,會造成張三的余額減少,而李四的余額并沒有增加。所以事務(wù)處理位于業(yè)務(wù)層,即一個service方法是不能分割的。 因此下一篇文章我們會學(xué)習(xí)到事務(wù)管理方案。一步步深入學(xué)習(xí),期待大家的支持啊。?

往期專欄&文章相關(guān)導(dǎo)讀?

?????大家如果對于本期內(nèi)容有什么不了解的話也可以去看看往期的內(nèi)容,下面列出了博主往期精心制作的Maven,Mybatis等專欄系列文章,走過路過不要錯過哎!如果對您有所幫助的話就點點贊,收藏一下啪。其中Spring專欄有些正在更,所以無法查看,但是當(dāng)博主全部更完之后就可以看啦。文章來源地址http://www.zghlxwxcb.cn/news/detail-475460.html

1. Maven系列專欄文章

Maven系列專欄 Maven工程開發(fā)
Maven聚合開發(fā)【實例詳解---5555字】

2. Mybatis系列專欄文章

Mybatis系列專欄 MyBatis入門配置
Mybatis入門案例【超詳細(xì)】
MyBatis配置文件 —— 相關(guān)標(biāo)簽詳解
Mybatis模糊查詢——三種定義參數(shù)方法和聚合查詢、主鍵回填
Mybatis動態(tài)SQL查詢 --(附實戰(zhàn)案例--8888個字--88質(zhì)量分)
Mybatis分頁查詢——四種傳參方式
Mybatis一級緩存和二級緩存(帶測試方法)
Mybatis分解式查詢
Mybatis關(guān)聯(lián)查詢【附實戰(zhàn)案例】
MyBatis注解開發(fā)---實現(xiàn)增刪查改和動態(tài)SQL
MyBatis注解開發(fā)---實現(xiàn)自定義映射關(guān)系和關(guān)聯(lián)查詢

3. Spring系列專欄文章?

Spring系列專欄 Spring IOC 入門簡介【自定義容器實例】
IOC使用Spring實現(xiàn)附實例詳解
Spring IOC之對象的創(chuàng)建方式、策略及銷毀時機和生命周期且獲取方式
Spring DI簡介及依賴注入方式和依賴注入類型
Spring IOC相關(guān)注解運用——上篇
Spring IOC相關(guān)注解運用——下篇
Spring AOP簡介及相關(guān)案例
注解、原生Spring、SchemaBased三種方式實現(xiàn)AOP【附詳細(xì)案例】
Spring事務(wù)簡介及相關(guān)案例
Spring 事務(wù)管理方案和事務(wù)管理器及事務(wù)控制的API
Spring 事務(wù)的相關(guān)配置、傳播行為、隔離級別及注解配置聲明式事務(wù)

到了這里,關(guān)于Spring事務(wù)簡介及相關(guān)案例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Spring MVC簡介附入門案例

    Spring MVC簡介附入門案例

    目錄 ? 一、SpringMVC簡介 1.1?MVC模型 1.2?SpringMVC 二、SpringMVC入門案例 2.1?創(chuàng)建項目 2.2?引入依賴和tomcat插件 2.3?修改web.xml文件? 2.4?新建springmvc.xml文件 2.5 編寫控制器? 2.6?配置運行方式 2.7?運行測試? 三、SpringMVC執(zhí)行流程 3.1?SpringMVC的組件 3.2?組件的工作流程 往期專欄文章

    2024年02月09日
    瀏覽(21)
  • 【Spring教程30】Spring框架實戰(zhàn):從零開始學(xué)習(xí)SpringMVC 之 Rest風(fēng)格簡介與RESTful入門案例

    【Spring教程30】Spring框架實戰(zhàn):從零開始學(xué)習(xí)SpringMVC 之 Rest風(fēng)格簡介與RESTful入門案例

    歡迎大家回到《Java教程之Spring30天快速入門》,本教程所有示例均基于Maven實現(xiàn),如果您對Maven還很陌生,請移步本人的博文《如何在windows11下安裝Maven并配置以及 IDEA配置Maven環(huán)境》,本文的上一篇為《SpringMVC 之 服務(wù)器響應(yīng)》 REST(Representational State Transfer),表現(xiàn)形式狀態(tài)轉(zhuǎn)

    2024年02月04日
    瀏覽(23)
  • AIGC:ChatGPT(一個里程碑式的對話聊天機器人)的簡介(意義/功能/核心技術(shù)等)、使用方法(七類任務(wù))、案例應(yīng)用(提問基礎(chǔ)性/事實性/邏輯性/創(chuàng)造性/開放性的問題以及編程相關(guān))之詳細(xì)攻略

    AIGC:ChatGPT(一個里程碑式的對話聊天機器人)的簡介(意義/功能/核心技術(shù)等)、使用方法(七類任務(wù))、案例應(yīng)用(提問基礎(chǔ)性/事實性/邏輯性/創(chuàng)造性/開放性的問題以及編程相關(guān))之詳細(xì)攻略

    AIGC:ChatGPT(一個里程碑式的對話聊天機器人)的簡介(意義/功能/核心技術(shù)等)、使用方法(七類任務(wù))、案例應(yīng)用(提問基礎(chǔ)性/事實性/邏輯性/創(chuàng)造性/開放性的問題以及編程相關(guān))之詳細(xì)攻略 導(dǎo)讀 :回?fù)艿?020年5月,OpenAI提出了更強大的GPT-3模型,如今已經(jīng)過去2年多了,當(dāng)人們還在

    2024年02月03日
    瀏覽(27)
  • [筆記]事務(wù)簡介-springboot

    在Spring Boot中,事務(wù)的管理通常通過注解來實現(xiàn),使得配置變得簡單而直觀。這種方式與Spring Boot的設(shè)計理念一致,即減少顯式配置,增加自動配置。以下是如何在Spring Boot項目中應(yīng)用和管理事務(wù)的詳細(xì)說明: Spring Boot事務(wù)基礎(chǔ) Spring Boot沿用了Spring的事務(wù)管理概念,但在配置和

    2024年01月25日
    瀏覽(10)
  • 事務(wù)相關(guān)概念

    事務(wù):邏輯上的一組操作,這些操作要么都成功,有一個失敗所有都失敗 1、臟讀:在數(shù)據(jù)庫訪問中,事務(wù)T1將某一值修改,然后事務(wù)T2讀取該值,此后T1因為某種原因撤銷對該值的修改,這就導(dǎo)致了T2所讀取到的數(shù)據(jù)是無效的。 2、不可重復(fù)讀:指在數(shù)據(jù)庫訪問中,一個事務(wù)范

    2023年04月17日
    瀏覽(20)
  • MySQL事務(wù)相關(guān)筆記

    MySQL事務(wù)相關(guān)筆記

    InnoDB 最大特點:支持 事務(wù) 和 行鎖 ; MyISAM 不支持事務(wù) 一個事務(wù)是由一條或者多條對數(shù)據(jù)庫操作的SQL語句所組成的一個 不可分割 的單元,只有當(dāng)事務(wù)中的所有操作都正常執(zhí)行完了,整個事務(wù)才會被提交給數(shù)據(jù)庫。事務(wù)有如下特性: 1.事務(wù)的所有SQL語句全部執(zhí)行成功,才能提

    2024年02月09日
    瀏覽(39)
  • python 相關(guān)框架事務(wù)開啟方式

    對于框架而言,各式API接口少不了伴隨著事務(wù)的場景,下面就列舉常用框架的事務(wù)開啟方法 注:利用begin_nested方法,會開啟一個子事務(wù)!實現(xiàn)數(shù)據(jù)庫變更需將子事務(wù)提交再將主事務(wù)提交才行 2.1、樣例模板 2.2、進化版

    2024年02月13日
    瀏覽(20)
  • 案例挑戰(zhàn)——事務(wù)傳播行為

    案例挑戰(zhàn)——事務(wù)傳播行為

    此前在項目開發(fā)過程中,使用到了事務(wù)的傳播行為。但是大多數(shù)情況下都是使用的事務(wù)默認(rèn)的傳播行為required。但是其實還有其他的傳播行為。所以特地的回顧和學(xué)習(xí)了事務(wù)的多種傳播行為。本篇博客從5w2h的角度來對事務(wù)的傳播行為進行學(xué)習(xí)和實踐。 事務(wù)的傳播行為其實指的

    2024年02月12日
    瀏覽(18)
  • 圖書機讀目錄MARC簡介,ISO格式目錄數(shù)據(jù)生成

    圖書機讀目錄MARC簡介,ISO格式目錄數(shù)據(jù)生成

    機讀目錄(Machine-Readable Catalogue,MARC),是利用計算機讀取和處理書目信息,是計算機編目的產(chǎn)品。 它以代碼形式和特定的結(jié)構(gòu)將書目信息記錄在計算機的存儲載體上,能夠被計算機識別并編輯輸出書目信息。 MARC起源于美國國會圖書館于1965年1月提出的“標(biāo)準(zhǔn)機器可讀目錄

    2024年02月06日
    瀏覽(14)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包