Spring的事务回滚,当且仅当捕获到RuntimeException类型异常时,才会回滚,对普通Exception异常无效。
以下是我Service层捕获异常,并抛出RuntimeException异常到Action层:
- @Override
- public void lock(String id) throws RuntimeException {
- try {
- this.loginUserDao.lock(id);
- LoginUser user = this.loginUserDao.findById(id);
- user.setSex("捕捉到异常后,抛出RuntimeException类型的异常");
- this.loginUserDao.save(user);
- } catch (Exception e) {
- // 捕捉到异常后,抛出RuntimeException类型的异常。
- // spring 事务只在捕足到RuntimeException异常时,才会回滚,对Exception无效
- throw new RuntimeException(e.getMessage());
- }
- }
- <!-- 为sessionFactory定义事务管理器 -->
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory">
- <ref local="sessionFactory" />
- </property>
- </bean>
- <!-- 定义事务拦截器 -->
- <bean id="transactionInterceptor"
- class="org.springframework.transaction.interceptor.TransactionInterceptor">
- <!-- 为事务拦截器注入一个事务管理器 -->
- <property name="transactionManager" ref="transactionManager" />
- <property name="transactionAttributes">
- <!-- 定义事务传播属性 PROPAGATION_REQUIRED:表示如果事务不存在,则创建一个新事务,如果存在,则加入到该事务。 -->
- <props>
- <prop key="save*">PROPAGATION_REQUIRED</prop>
- <prop key="add*">PROPAGATION_REQUIRED</prop>
- <prop key="delete*">PROPAGATION_REQUIRED</prop>
- <prop key="update*">PROPAGATION_REQUIRED</prop>
- <prop key="lock*">PROPAGATION_REQUIRED</prop>
- <prop key="unLock*">PROPAGATION_REQUIRED</prop>
- <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
- </props>
- </property>
- </bean>
- <!-- 定义拦截器要拦截的bean -->
- <bean id="autoProxy"
- class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
- <property name="beanNames">
- <list>
- <!-- 拦截所有名字以Service结尾的bean进行代理 -->
- <value>*Service</value>
- </list>
- </property>
- <property name="interceptorNames">
- <list>
- <value>transactionInterceptor</value>
- </list>
- </property>
- </bean>