java 如何在抛出异常时回滚Spring事务

uplii1fm  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(150)

我正在使用spring3.0.5和hib3.6。在我的项目中,有一个场景是我必须回滚抛出的任何异常事务或发生错误。这是示例代码,一切正常,除了当我抛出异常时事务不会回滚,但如果抛出任何异常,如mysql.IntegrityConstraintException,则事务会回滚。为什么我的情况没有发生

应用程序上下文.xml

<bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:database.properties"/>
    </bean>
      <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />

        </bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
 <property name="dataSource" ref="myDataSource" />
    <property name="packagesToScan" value="com.alw.imps"/>
    <property name="configLocation">    
        <value>
            classpath:hibernate.cfg.xml
        </value>
     </property>
    </bean>

    <bean id="stateDao" class="com.alw.imps.dao.StateDaoImpl">
     <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

        <bean id="stateService" class="com.alw.imps.services.StateService">
       <property name="stateDao" ref="stateDao"></property>
       <property name="cityDao" ref="cityDao"></property>
       <property name="customerDao" ref="customerDao"></property>
       </bean>  

        <bean id="customerDao" class="com.alw.imps.dao.CustomerDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
       </bean> 

            <bean id="cityDao" class="com.alw.imps.dao.CityDaoImpl">
              <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>  



<tx:annotation-driven transaction-manager="transactionManager"  />

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>        

<tx:advice id = "txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>

服务类状态服务

@Transactional(rollbackFor={Exception.class})
public class StateService {

  private StateDaoImpl stateDao;
  private CityDao cityDao;
  private CustomerDao customerDao;

  public void setCustomerDao(CustomerDao customerDao) {
    this.customerDao = customerDao;
  }

  public void setStateDao(StateDaoImpl stateDao) {
    this.stateDao = stateDao;
  }

  public CityDao getCityDao() {
    return cityDao;
  }

  public void setCityDao(CityDao cityDao) {
    this.cityDao = cityDao;
  }

  public void addState() {
    try {
      State state=new State();
      state.setStateName("Delhi");
      stateDao.create(state);
      addCity();
      addCustomer();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void addCity() throws Exception {
    City city=new City();
    city.setCiytName("Delhi");
    city.setStateId(1);
    cityDao.create(city);
  }

  public void addCustomer() throws Exception {
    throw new java.lang.Exception();
  }

DAO

public class StateDaoImpl extends GenericDaoImpl<State, Integer> implements StateDao {
}

泛型实现

public class GenericDaoImpl<T,PK extends Serializable> implements GenericDao<T,PK> {
  public SessionFactory sessionFactory;
  public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }

  public Session getSession() {
    return sessionFactory.getCurrentSession();
  }

  public PK create(T o) {
    Session ss= getSession();
    ss.save(o);
    return null;
  }

休眠配置文件

<hibernate-configuration>
  <session-factory>
    <property name="connection.pool_size">1</property>
    <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    <property name="defaultAutoCommit">false</property>
    <mapping class="com.alw.imps.pojo.State"/>
    <mapping class="com.alw.imps.pojo.City"/> 
  </session-factory>
</hibernate-configuration>

正如我所说,我的问题是当我从方法addCustomer()抛出类型为Exception的异常时,事务没有得到回滚

kpbwa7wx

kpbwa7wx1#

由于没有引发异常,因此您的事务不会回滚:你调用的addState()方法会捕获异常:

public void addState() {
    try {
        State state=new State();
        state.setStateName("Delhi");
        stateDao.create(state);
        addCity();
        addCustomer();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

因此,事务性Spring代理不会看到任何抛出的异常,也不会回滚事务。
它适用于从DAO抛出的异常,因为DAO本身就是事务性的,所以它自己的事务性代理检测到DAO抛出的异常,并将事务标记为回滚。然后异常被传播到服务并被代码捕获,但此时事务已经被标记为回滚。

3hvapo4f

3hvapo4f2#

您的事务不会回滚,因为您没有让Exception到达Spring框架,而是在代码本身中捕获异常。

public void addState() 
{
        try
        {
        State state=new State();
        state.setStateName("Delhi");
        stateDao.create(state);
        addCity();
        addCustomer();
        }
        catch(Exception e)
        {

            e.printStackTrace();
        }
}

使用

public void addState() 
{
        State state=new State();
        state.setStateName("Delhi");
        stateDao.create(state);
        addCity();
        addCustomer();
}
nvbavucw

nvbavucw3#

事务尚未回滚,因为您正在通过编写catch块自行捕获异常。
这可以在正常情况下完成,但在spring事务中,如果您这样做,spring事务管理器如何知道异常正在发生......这就是它没有回滚的原因。

q0qdq0h2

q0qdq0h24#

您可以在Spring API文档中找到大多数问题的答案。@Transactional包含一个字段Class<? extends Throwable>[] rollbackFor()
默认情况下,事务将在RuntimeExceptionError上回退,但不会在选中的异常(业务异常)上回退。有关详细说明,请参阅org.springframework.transaction.interceptor.DefaultTransactionAttribute.rollbackOn(Throwable)
这意味着,对于以下情况,无论调用方如何处理异常,默认情况下只有第一个RunTimeException情况会调用回滚。

// Only this case would roll back by default
@Override
@Transactional
public void testRollbackRuntimeException() {
    // jpa operation.
    throw new RuntimeException("test exception");
}

// never roll back, because its caught.
@Override
@Transactional
public void testRollbackRuntimeExceptionCaught() {
    try {
        throw new RuntimeException("test exception");
    } catch(Exception e) {}
}

// @Transactional(rollbackFor = Exception.class) would also rollback. but by default no
@Override
@Transactional
public void  testRollBackWithExceptionCaught() throws Exception {
    throw new Exception("test exception");
}

// never roll back because the checked exception is caught.
@Override
@Transactional
public void  testRollBackWithExceptionCaught() {
    try {
        throw new Exception("test exception");
    } catch (Exception e) {}
}

通常,您可能希望使用@Transactional(rollbackFor = Exception.class)无差别地回滚已检查的异常

相关问题