spring_(23)Spring_事務準備和宣告式事務md
阿新 • • 發佈:2018-12-09
事務簡介
- 事務管理是企業級應用程式開發中必不可少的技術,用來確保資料的完整性和一致性。
- 事務就是一系列的動作,它們被當做一個單獨的工作單元。這些動作要麼全部完成,要麼全部不起作用。
- 事務的四個關鍵屬性(ACID)
- 原子性(atomicity):事務是一個原子操作,由一系列動作組成。事務的原子性確保動作要麼全部完成要麼完全不起作用。
- 一致性(consistency):一旦所有事務動作完成,事務就被提交。資料和資源就處於一種滿足業務規則的一致性狀態中。
- 隔離性(isolation):可能有許多事務會同時處理相同的資料,因此每個事務都應該與其他事務隔離開來,防止資料損壞。
- 永續性(durability):一旦事務完成,無論發生什麼系統錯誤,他的結果都不應該受到影響。通常情況下,事務的結果被寫到持久化儲存器中。
Spring中的事務管理器
- Spring從不同的事務管理API中抽象了一整套的事務機制。開發人員不必瞭解底層的事務API,就可以利用這些事務機制。有了這些事務機制,事務管理程式碼就能獨立於特定的事務技術了。
- Spring的核心事務管理抽象是Interface PlatformTransactionManager管理封裝了一組獨立於技術的方法。無論使用Spring的哪種事務管理策略(程式設計式或宣告式),事務管理器都是必須的。
Spring中的事務管理器的不同實現
- Class DataSource TransactionManager :在應用程式中只需要處理一個數據源,而且通過JDBC存取
- Class Jta TransactionManager:在JavaEE應用伺服器上用JTA(Java Transaction API)進行事務管理
- Class Hibernate TansactionManager:用Hibernate框架存取資料庫
- …
- 事務管理器以普通的Bean形式宣告在Spring IOC容器中
例子程式
基本結構
BookShopDao.java
package com.spring.tx;
public interface BookShopDao {
//根據書號獲取書的單價
public int findBookPriceByIsbn(String isbn);
//更新書的庫存,使書號對應的庫存-1
public void updateBookStock(String isbn);
//更新使用者的賬戶餘額:使username的balance-price
public void updateUserAccount(String username,int price);
}
BookShopDaoImpl.java
package com.spring.tx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookShopDaoImpl implements BookShopDao{
@Autowired //自動地注入進去
private JdbcTemplate jdbcTemplate;
@Override
public int findBookPriceByIsbn(String isbn) {
String sql = "SELECT price FROM book WHERE isbn = ?";
return jdbcTemplate.queryForObject(sql,Integer.class,isbn);
}
@Override
public void updateBookStock(String isbn) {
//檢查賬戶書的庫存是否足夠,若不夠免責丟擲異常
String sql2 = "SELECT stock FROM book_stock WHERE isbn = ?";
int stock = jdbcTemplate.queryForObject(sql2,Integer.class,isbn);
if(stock==0){
throw new BookStockException("庫存不足!");
}
String sql = "UPDATE book_stock SET stock = stock -1 WHERE isbn = ?";
jdbcTemplate.update(sql,isbn);
}
@Override
public void updateUserAccount(String username, int price) {
//驗證餘額是否足夠,若不足,則丟擲異常
String sql2 = "SELECT balance FROM account WHERE username = ?";
int balance = jdbcTemplate.queryForObject(sql2,Integer.class,username);
if(balance<price){
throw new UserAccountException("餘額不足!");
}
String sql = "UPDATE account SET balance = balance - ? WHERE username = ?";
jdbcTemplate.update(sql,price,username);
}
}
BookShopService.java
package com.spring.tx;
public interface BookShopService {
public void purchase(String username,String isbn);
}
BookShopServiceImpl.java
package com.spring.tx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService{
@Autowired
private BookShopDao bookShopDao;
//新增事務註解
@Transactional
@Override
public void purchase(String username, String isbn) {
//1.獲取書的單價
int price = bookShopDao.findBookPriceByIsbn(isbn);
//2.更新書的庫存
bookShopDao.updateBookStock(isbn);
//3.更新使用者的餘額
bookShopDao.updateUserAccount(username,price);
}
}
BookStockException.java
package com.spring.tx;
public class BookStockException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
public BookStockException() {
super();
}
public BookStockException(String message) {
super(message);
}
public BookStockException(String message, Throwable cause) {
super(message, cause);
}
public BookStockException(Throwable cause) {
super(cause);
}
protected BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
UserAccountException.java
package com.spring.tx;
public class UserAccountException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
public UserAccountException() {
super();
}
public UserAccountException(String message) {
super(message);
}
public UserAccountException(String message, Throwable cause) {
super(message, cause);
}
public UserAccountException(Throwable cause) {
super(cause);
}
protected UserAccountException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
db.properties
jdbc.user=root
jdbc.password=etron
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.initPoolSize=5
jdbc.maxPoolSize=50
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" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.spring"></context:component-scan>
<!-- 匯入資原始檔 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置C3P0資料來源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!--配置Spring的JdbcTemplate-->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置 NamedParameterJdbcTemplate , 該物件可以使用具名引數,其沒有無引數的狗在其,所以必須為其構造器指定引數-->
<bean id="namedParameterJdbcTemplate"
class = "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!--配置事務管理器-->
<bean id = "transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--啟用事務註解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
SpringTransactionTest.java
package com.spring.tx;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTransactionTest {
private ApplicationContext ctx = null;
private BookShopDao bookShopDao = null;
private BookShopService bookShopService = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopDao = ctx.getBean(BookShopDao.class);
bookShopService = ctx.getBean(BookShopService.class);
}
public void testBookShopService(){
bookShopService.purchase("AA","1001");
}
public void testBookShopDaoFindPriceByIsbn(){
System.out.println(bookShopDao.findBookPriceByIsbn("1001"));
}
public void testBookShopDaoUpdateUserAccount(){
bookShopDao.updateUserAccount("AA",200);
}
public void testBookShopDaoUpdateBookStock(){
bookShopDao.updateBookStock("1001");
}
public static void main(String[] args){
/*new SpringTransactionTest().testBookShopDaoFindPriceByIsbn();
new SpringTransactionTest().testBookShopDaoUpdateBookStock();
new SpringTransactionTest().testBookShopDaoUpdateUserAccount();*/
new SpringTransactionTest().testBookShopService();
}
}
資料庫看結果