SSM框架+MySQL資料庫配置事務管理
阿新 • • 發佈:2018-11-10
資料庫事務(Database Transaction) ,是指作為單個邏輯工作單元執行的一系列操作,要麼完全地執行,要麼完全地不執行。
例如銀行轉賬,A賬戶轉100元給B賬戶,正常的流程是A賬戶減掉100元,B賬戶增加100元。如果轉賬失敗的話,不能出現A賬戶已經減掉100元而B賬戶沒有增加100元的情況。這個時候就需要用到事務,要麼B賬戶增加了100元,全部執行完成,要麼全部不執行。
SSM框架中事務的配置步驟如下:
首先配置spring-mybatis.xml,加入以下:
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--開啟註解事務--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
如果報錯的話,在開頭部分加入以下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
然後去需要進行事務管理的service層實現方法上加入@Transactional:
@Transactional @Override public int addNewOrder(Map<String, Object> params) { int result = 0; //新增訂單 result = orderDao.addNewOrder(params); if(result > 0){ int uid = Integer.parseInt(params.get("uid").toString()); //新增訂單詳情 int outcome = orderDao.addNewOrderItem(uid); if(outcome > 0){ //扣除金額 ... //減去商品庫存 ... //清空購物車 ... }else{ throw new RuntimeException("新增訂單詳情失敗"); } }else{ throw new RuntimeException("新增訂單失敗"); } return result; }
以訂單付款為例子,部分程式碼省略,能看懂意思就行。接著在controller層try catch一下:
int result =0;
try {
result = orderService.addNewOrder(params);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
這樣,就可以對資料庫進行事務管理了。
另外補充一點,我在查閱SSM+MySQL事務管理的時候,有博主提到需要設定MySQL的資料庫引擎為INNODB,我的預設是INNODB,不是的話需要修改為INNODB。檢視資料庫引擎的方法:進入cmd,輸入mysql -u root -p,回車然後輸入密碼,接著輸入:show engines;欄位 Support為:Default表示預設儲存引擎。
修改的話,另行百度吧,這裡不再贅述了。