昨日我們講解了什麼事Transaction、Transaction的特性以及用一個例子說明沒有事務管理的情形會發生什麼樣子的事。
今日我們將介紹Spring 如何設定Declarative transaction management與如何透過transaction management修正昨日的例子
Spring 透過Transaction manager管理事務,實現PlatformTransactionManager,除了整合原生JDBC的DataSourceTransactionManager,亦提供Hibernate、Jpa等整合方案。
<?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 https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 加載外部文件 -->
<context:property-placeholder location="classpath:dbconfig.properties"></context:property-placeholder>
<context:component-scan base-package="com.swj"></context:component-scan>
<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>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
<!-- transaction management -->
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="tx"></tx:annotation-driven>
</beans>
為transferMoney方法加上註解
@Service
public class AccountService {
@Autowired
private AccountDao accountDao;
@Transactional
public void transferMoney(String from, String to , Integer amount){
accountDao.addMoney(to,amount);
int a =1/0;
accountDao.minusMoney(from,amount);
System.out.println("轉帳完成:"+from+" to "+to+" 金額:"+amount);
}
}
Result
接下來介紹@Transactional的設定參數
設置transaction超過時間就rollback
@Transactional(timeout = 3)
public void transferMoney(String from, String to , Integer amount){
accountDao.addMoney(to,amount);
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
accountDao.minusMoney(from,amount);
System.out.println("轉帳完成:"+from+" to "+to+" 金額:"+amount);
}
設置readOnly=true可以加快查詢速度,預設為false