Spring提供了2種事務管理html
新建包com.chy.dao,包下新建接口AccountDao、實現類AccountDaoImpl:mysql
public interface AccountDao { //查詢用戶帳戶上的餘額 public double queryMoney(int id); //減小用戶帳戶上的餘額 public void reduceMoney(int id, double amount); //增長用戶帳戶上的餘額 public void addMoney(int id, double amount); }
@Repository public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao { @Override public double queryMoney(int id) { String sql = "select money from account_tb where id=?"; JdbcTemplate jdbcTemplate = super.getJdbcTemplate(); double money = jdbcTemplate.queryForObject(sql, double.class,id); return money; } @Override public void reduceMoney(int id, double account) { double money = queryMoney(id); money -= account; if (money>=0){ String sql = "update account_tb set money=? where id=?"; JdbcTemplate jdbcTemplate = super.getJdbcTemplate(); jdbcTemplate.update(sql, money, id); } //此處省略餘額不足時的處理 } @Override public void addMoney(int id, double account) { double money = queryMoney(id); money += account; String sql = "update account_tb set money=? where id=?"; JdbcTemplate jdbcTemplate = super.getJdbcTemplate(); jdbcTemplate.update(sql, money, id); } }
新建包com.chy.service,包下新建接口TransferService、實現類TransferServiceImpl:spring
public interface TransferService { public void transfer(int from,int to,double account); }
@Service public class TransferServiceImpl implements TransferService { private AccountDao accountDao; @Autowired public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void transfer(int from, int to, double account) { accountDao.reduceMoney(from,account); // System.out.println(1/0); accountDao.addMoney(to,account); } }
src下新建db.properties:sql
#mysql數據源配置 url=jdbc:mysql://localhost:3306/my_db?serverTimezone=GMT user=chy password=abcd
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入數據庫配置信息 --> <context:property-placeholder location="db.properties" /> <!-- 使用包掃描--> <context:component-scan base-package="com.chy.dao,com.chy.service" /> <!-- 配置數據源,此處使用jdbc數據源 --> <bean name="jdbcDataSource" class="com.mysql.cj.jdbc.MysqlDataSource"> <property name="url" value="${url}" /> <property name="user" value="${user}" /> <property name="password" value="${password}" /> </bean> <!-- 配置AccountDaoImpl,注入數據源 --> <bean name="accountDaoImpl" class="com.chy.dao.AccountDaoImpl"> <!--注入數據源--> <property name="dataSource" ref="jdbcDataSource" /> </bean> </beans>
新建包com.chy.test,包下新建主類Test:數據庫
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml"); TransferServiceImpl transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferServiceImpl.class); transferServiceImpl.transfer(1,2,1000);
以上是未使用事務管理的,將service層的這句代碼取消註釋,會出現錢轉丟的狀況(對方收不到錢)。express
// System.out.println(1/0);
編程式事務管理,顧名思義須要本身寫代碼。編程
本身寫代碼很麻煩,spring把代碼封裝在了TransactionTemplate類中,方便了不少。app
@Service public class TransferServiceImpl implements TransferService { private AccountDao accountDao; private TransactionTemplate transactionTemplate; @Autowired public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Autowired public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } @Override public void transfer(int from, int to, double account) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { accountDao.reduceMoney(from, account); // System.out.println(1 / 0); accountDao.addMoney(to, account); } }); } }
transactionTemplate.execute(new TransactionCallbackWithoutResult() { });
使用匿名內部類傳入一個TransactionCallbackWithoutResult接口類型的變量,只需實現一個方法:把原來處理業務的代理都放到這個方法中。ide
<!-- 配置事務管理器,此處使用JDBC的事務管理器--> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數據源--> <property name="dataSource" ref="jdbcDataSource" /> </bean> <!-- 配置事務管理模板--> <bean class="org.springframework.transaction.support.TransactionTemplate"> <!-- 注入事務管理器 --> <property name="transactionManager" ref="transactionManager" /> </bean>
把下面這句代碼取消註釋,運行,不會出現錢轉丟的狀況(執行失敗,自動回滾):測試
// System.out.println(1/0);
聲明式事務管理,無論是基於xml,仍是基於註解,都有如下3個點要注意:
TransferService transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferService.class);
紅色標出的2處只能使用接口。
<!-- 配置事務管理器,此處使用JDBC的事務管理器--> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數據源--> <property name="dataSource" ref="jdbcDataSource" /> </bean> <!-- 配置加強--> <!-- 此處只能用id,不能用name。transaction-manager指定要引用的事務管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 配置要添加事務的方法,直接寫方法名便可。能夠有多個method元素,可使用通配符* --> <tx:method name="transfer" /> </tx:attributes> </tx:advice> <!-- 配置aop--> <aop:config> <!-- 配置切入點--> <aop:pointcut id="transferPointCut" expression="execution(* com.chy.service.TransferServiceImpl.transfer(..))"/> <!--指定要引用的<tx:advice>,指定切入點。切入點能夠point-ref引用,也能夠pointcut現配。能夠有多個advisor元素。 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="transferPointCut"/> </aop:config>
<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT" read-only="false" />
propagation 指定事務的傳播行爲,默認爲REQUIRED
isolation 指定事務的隔離級別
read-only 是否只讀,讀=>查詢,寫=>增刪改。默認爲false——讀寫。
這4個屬性通常都不用設置,使用默認值便可。固然,只查的時候,能夠設置read-only="true"。
<tx:method name="transfer" />
<tx:method name="*" />
<tx:method name="save*" /> <tx:method name="find*" read-only="false"/> <tx:method name="update*" /> <tx:method name="delete*" />
由於要配合aop使用,篩選範圍是切入點指定的方法,不是項目中全部的方法。
好比
<tx:method name="save*" />
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.chy.service.TransferServiceImpl.*(..))" />
切入點是TransferServiceImpl類中的全部方法,是在TransferServiceImpl類全部方法中找到以save開頭的全部方法,給其添加事務。
<!-- 配置事務管理器,此處使用JDBC的事務管理器--> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數據源--> <property name="dataSource" ref="jdbcDataSource" /> </bean> <!--啓用事務管理的註解,並指定要使用的事務管理器 --> <tx:annotation-driven transaction-manager="transactionManager" />
@Service // @Transactional public class TransferServiceImpl implements TransferService { private AccountDao accountDao; @Autowired public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override @Transactional public void transfer(int from, int to, double account) { accountDao.reduceMoney(from, account); // System.out.println(1 / 0); accountDao.addMoney(to, account); } }
能夠標註在業務層的實現類上,也能夠標註在處理業務的方法上。
標註在類上,會給這個全部的業務方法都添加事務;標註在業務方法上,則只給這個方法添加事務。
一樣能夠設置傳播行爲、隔離級別、是否只讀:
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
基於註解的聲明式事務管理是最簡單的,推薦使用。
緣由:IDEA自動引入的約束不對。
IDEA會自動引入所需的約束,但spring事務管理所需的約束,IDEA引入的不對。
<?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/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
看我紅色標出的部分(需拖動滾動條查看最右邊),這是IDEA自動引入的tx的約束,這是舊版本的約束,已經無效了。
新版本的約束:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi裏對應的部分也要修改:
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
能夠在錯誤約束的基礎上改,也能夠添加。
若是沒有修改xsi中對應的部分,會報下面的錯:
通配符的匹配很全面, 但沒法找到元素 'tx:advice' 的聲明。
通配符的匹配很全面, 但沒法找到元素 'tx:annotation-driven' 的聲明。
上面提供的約束是目前版本的約束,之後可能會變。最好在官方文檔中找,有2種方式:
(1)http://www.springframework.org/schema/tx/spring-tx.xsd 可修改此url查看其它約束
(2)若是下載了spring的壓縮包,可在schema文件夾下查看約束。
spring壓縮包的下載可參考:http://www.javashuo.com/article/p-yscxladi-ko.html