目錄
?
一、事務(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 transaction和end 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ù)庫里面的情況是怎么樣的。
????????此時沒有事務(wù)管理,會造成張三的余額減少,而李四的余額并沒有增加。所以事務(wù)處理位于業(yè)務(wù)層,即一個service方法是不能分割的。 因此下一篇文章我們會學(xué)習(xí)到事務(wù)管理方案。一步步深入學(xué)習(xí),期待大家的支持啊。?文章來源:http://www.zghlxwxcb.cn/news/detail-475460.html
往期專欄&文章相關(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)!