為什麼加個註解@Transtaional就可以保證事務的一致性和完整性?
阿新 • • 發佈:2019-06-16
<?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:aop="http://www.springframework.org/schema/aop" 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:component-scan base-package="com.atguigu.book_xml"></context:component-scan> <!-- 引入屬性檔案 --> <context:property-placeholder location="db.properties"/> <!-- 建立資料來源 --> <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> <!-- 通過資料來源配置JdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事務管理器,不管是用註解方式或xml方式配置事務,一定要有DataSourceTransactionManager事務管理器的支援 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事務通知 --> <tx:advice id="tx" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <!-- 在設定好的切入點表示式下再次進行事務設定 --> <tx:method name="buyBook"/> <tx:method name="checkOut"/> <!-- 只有select開頭的方法才會被事務處理 --> <tx:method name="select*" read-only="true"/> <tx:method name="insert*"/> <tx:method name="update*"/> <tx:method name="delete*"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置切入點表示式 --> <aop:config> <aop:pointcut expression="execution(* com.atguigu.book_xml.service.impl.*.*(..))" id="pointCut"/> <aop:advisor advice-ref="tx" pointcut-ref="pointCut"/> </aop:config> </beans>
在xml裡面定義了資料來源bean,資料來源bean又被事務管理器bean鎖依賴,這時候用的資料來源連線物件connection就是同一個,spring管理物件預設為單例
package com.atguigu.book.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.atguigu.book.service.BookService; import com.atguigu.book.service.Cashier; @Controller public class BookController { @Autowired private BookService service; @Autowired private Cashier cashier; public void buyBook() { service.buyBook("1", "1001"); } public void checkOut() { List<String> bids = new ArrayList<>(); bids.add("1"); bids.add("2"); cashier.checkOut("1001", bids); } }
package com.atguigu.book.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.atguigu.book.service.BookService; import com.atguigu.book.service.Cashier; @Service @Transactional public class CashierServiceImpl implements Cashier { @Autowired private BookService service; @Override public void checkOut(String uid, List<String> bids) { for (String bid : bids) { service.buyBook(bid, uid); } } }
package com.atguigu.book.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.book.dao.BookDao;
import com.atguigu.book.exception.MyException;
import com.atguigu.book.service.BookService;
@Service
//@Transactional
public class BookServiceImpl implements BookService {
@Autowired
private BookDao dao;
/**
* @Transactional:對方法中所有的操作作為一個事務進行管理
* 在方法上使用,只對方法有效果
* 在類上使用,對類中所有的方法都有效果
* @Transactional中可以設定的屬性:
*
* propagation:A方法和B方法都有事務,當A在呼叫B時,會將A中的事務傳播給B方法,B方法對於事務的處理方式就是事務的傳播行為
* Propagation.REQUIRED:必須使用呼叫者的事務
* Propagation.REQUIRES_NEW:將呼叫者的事務掛起,不使用呼叫者的事務,使用新的事務進行處理
*
* isolation:事務的隔離級別,在併發的情況下,操作資料的一種規定
* 讀未提交:髒讀 1
* 讀已提交:不可重複讀 2
* 可重複讀:幻讀 4
* 序列化:效能低,消耗大 8
*
*
* timeout:在事務強制回滾前最多可以執行(等待)的時間
*
* readOnly:指定當前事務中的一系列的操作是否為只讀
* 若設定為只讀,不管事務中有沒有寫的操作,mysql都會在請求訪問資料的時候,不加鎖,提高效能
* 但是如果有寫操作的情況,建議一定不能設定只讀
*
* rollbackFor|rollbackForClassName|noRollbackFor|noRollbackForClassName:設定事務回滾的條件
*/
@Transactional(propagation=Propagation.REQUIRES_NEW, timeout=3, noRollbackFor= {NullPointerException.class, MyException.class})
public void buyBook(String bid, String uid) {
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Integer price = dao.selectPrice(bid);
dao.updateSt(bid);
dao.updateBalance(uid, price);
}
}
package com.atguigu.book.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.atguigu.book.dao.BookDao;
import com.atguigu.book.exception.MyException;
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer selectPrice(String bid) {
Integer price = jdbcTemplate.queryForObject("select price from book where bid = ?", new Object[] {bid}, Integer.class);
return price;
}
@Override
public void updateSt(String bid) {
//獲取該書籍的庫存
Integer st = jdbcTemplate.queryForObject("select st from stock where sid = ?", new Object[] {bid}, Integer.class);
if(st <= 0) {
throw new RuntimeException();
}else {
jdbcTemplate.update("update stock set st = st -1 where sid = ?", bid);
}
}
@Override
public void updateBalance(String uid, Integer price) {
Integer balance = jdbcTemplate.queryForObject("select balance from money where uid = ?", new Object[] {uid}, Integer.class);
if(balance < price) {
throw new MyException("餘額不足");
}else {
jdbcTemplate.update("update money set balance = balance - ? where uid = ?", price, uid);
}
}
}