web项目下使用spring框架进行事务管理,导入spring的相关jar包之后,在spring的配置文件中添加下列配置信息:
<!-- 使用JDBC事物 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" /><span style="font-family: Arial, Helvetica, sans-serif;"><!-- 数据源 --></span>
</bean>
<!-- AOP配置事物 需要监控的对数据库的操作方法-->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP切面 扫面下面路径显得文件,有上面方法名称的方法全部加入管理-->
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com..service.*.*(..))"/>
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/>
</aop:config>
<!-- 使用annotation注解方式配置事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
在上面的切面扫描路径下添加对应的方法,如:
<pre name="code" class="java">@Override
public void add() throws Exception {
String msg = ..dao.add();
//
if(!"success".equals(<span style="font-family:Arial, Helvetica, sans-serif;">msg</span>)){
throw new RuntimeException(retMsg);
}
}
默认情况下spring只对运行时异常会触发事务回滚,所以如果想自定义抛出异常时必须抛出RuntimeException异常,抛出Exception不会回滚。
如果想抛出任何异常都事务回滚,可以在事务配置的扫描方法里添加配置,如下:<pre name="code" class="html"><tx:method name="*" read-only="false" rollback-for="java.lang.Exception"/>