Spring框架最核心功能之一就是事務管理,Spring支持聲明式事務和編程式事務事務類型,這能幫助咱們:java
Spring框架支持事務管理的核心是事務管理器抽象,經過定義接口 PlatformTransactionManager 讓不一樣數據訪問框架來實現,mysql
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }
getTransaction():返回一個已經激活的事務或建立一個新的事務(根據給定的TransactionDefinition類型參數定義的事務屬性),返回的是TransactionStatus對象表明了當前事務的狀態,其中該方法拋出TransactionException(未檢查異常)表示事務因爲某種緣由失敗。
commit():用於提交TransactionStatus參數表明的事務
rollback():用於回滾TransactionStatus參數表明的事務spring
TransactionDefinition接口sql
public interface TransactionDefinition { int getPropagationBehavior(); int getIsolationLevel(); int getTimeout(); boolean isReadOnly(); String getName(); }
配置文件數據庫
<bean id="dataSource" parent="dataSourceParent"> <property name="url" value="jdbc:mysql://dbm.***.me:3306" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); jdbcTemplate.execute(CREATE_TABLE_SQL); try { jdbcTemplate.update(INSERT_SQL, "test"); txManager.commit(status); ![](http://images2015.cnblogs.com/blog/1071030/201706/1071030-20170608143321590-1214373007.png) } catch (RuntimeException e) { txManager.rollback(status); }
<tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED"/> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="daoMethod" expression="execution(* com.dao.*.*(..))"/> <aop:advisor pointcut-ref="daoMethod" advice-ref="txadvice"/> </aop:config>