Spring配置事务
Spring配置事务
前言
使用Spring框架在XML中配置事务。为数据库操作提供了一个从失败中恢复到正常状态的方法,同时提供了数据库即使在异常状态下仍能保持一致性的方法。当多个应用程序在并发访问数据库时,可以在这些应用程序之间提供一个隔离方法,以防止彼此的操作互相干扰。
在XML中自定义配置事务
1) 在spirng的xml中装配DataSourceTransactionManager用于连接数据库
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
2) 声明事务规则、指定在那些sql语句中才执行事务
<tx:advice id="txAdvice" transaction-manager="txManager">
<!--定义属性,声明事务规则-->
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS"/>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
3) 使用AOP切面、指定在哪些方法或类中执行事务
<aop:config>
<aop:pointcut id="serviceMethod" expression="execution(* cn.test..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>
Spring使用注解开启事务
@Transactional注解指定某个类与上面第3步类似。也可以指定在方法上单独让某个方法执行事务。同样需要先装配一个连接数据源的Bean使用以下标签进行连接同时开启注解事务。
@Transactional 添加在类上或方法上
<tx:annotation-driven transaction-manager="txManager"/>
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Slikeの后花园!