spring-transaction事务

其实一个事务对应的就是一个方法

 

基于注解的方式实现事务
1.
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
2.
<tx:annotation-driven transaction-manager="transactionManager"/>
3.
@Transactional
public void purchase(int accountId,int bookId)

@Transactional(isolation=Isolation.READ_COMMITTED,
noRollbackFor=NumberException.class,
propagation=Propagation.REQUIRES_NEW,
readOnly=false,
timeout=3)
isolation=Isolation.READ_COMMITTED:事务的隔离级别
noRollbackFor=NumberException.class:遇到哪些异常不回滚
propagation=Propagation.REQUIRES_NEW:事务的传播行为,当一个事务方法调用另一个事务方法时,新开一事务
Propagation.REQUIRED:当一个事务方法调用另一个事务方法时,合为一个事务

注意:事务的传播行为是在本事务被另一个事务调用时才起作用的


readOnly=false:事务对数据库只读
timeout=3: 当此事务执行的时间超过3秒时就回滚

基于配置文件的方式实现事务
<!-- 基于配置文件的方式配置 -->
<!-- 1.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 2.配置事务属性。需要一个事务管理器。支持对方法名加通配符 -->
<tx:advice transaction-manager="transactionManager" id="advice">
<tx:attributes>
<tx:method name="purchase" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--
3.配置事务切入点,并把它和事务属性关联起来
expression="execution(* transaction_xml.BookStoreService.*(..))" 通配事务的那个方法

-->
<aop:config>
<aop:pointcut expression="execution(* transaction_xml.BookStoreService.*(..))" id="pointcut"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config>

posted @ 2017-03-08 20:04  逢甘霖成大事  阅读(374)  评论(0编辑  收藏  举报