【问题标题】:how to use transaction of spring to rollback the changes when checked exception is caught?捕获到检查的异常时如何使用spring的事务来回滚更改?
【发布时间】:2013-05-31 11:40:25
【问题描述】:

我正在开发一个具有 JSF、Spring 和 Hibernate 框架的应用程序。 我正在尝试使用以下方法测试 Spring 的事务。

@Override
@Transactional(rollbackFor=UnsupportedOperationException.class, propagation=Propagation.REQUIRED)
public void updateActiveMonth(Long collectionMonthId) throws Exception{
    try{
    Session session = getSessionFactory().getCurrentSession();
    String hql = "update CollectionMonth collectionMonth set active = false";
    Query query = session.createQuery(hql);
    query.executeUpdate();
    if (true) {
        throw new UnsupportedOperationException();
    }
    String hql1 = "update CollectionMonth collectionMonth set collectionMonth.active = true where collectionMonth.id=:collectionMonthId";
    Query query1 = session.createQuery(hql1);
    query1.setLong("collectionMonthId", collectionMonthId);
    query1.executeUpdate();
    }catch(UnsupportedOperationException e){
        throw e;
    }
}

上述方法假设回滚第一个查询所做的更新,但这不会发生。

在应用程序上下文中,我有以下设置

<context:annotation-config/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
      p:driverClassName="${jdbc.driverClassName}"
      p:url="${jdbc.url}"
      p:username="${jdbc.username}"
      p:password="${jdbc.password}"/>


<!-- PERSISTENCE SUPPORT HERE (Hibernate 4 Mapping In Spring ) -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
      p:dataSource-ref="dataSource"
      p:configLocation="/WEB-INF/hibernate.cfg.xml" 
      p:packagesToScan="collection.model"/>

    <!-- Transaction Manager is defined -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
      p:sessionFactory-ref="sessionFactory" />

<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>

谁能告诉我我做错了什么?

【问题讨论】:

  • 即使没有特殊注释,事务也会回滚。简单案例是否适合您,而您仅在特定配置方面有问题?
  • 在我的情况下,事务在有注释和没有注释的情况下都没有回滚。

标签: java spring hibernate spring-transactions


【解决方案1】:

我想你忘记将你的类声明为 spring bean,所以 spring 容器能够检测和注册它们。您的方法 public void updateActiveMonth(Long collectionMonthId) 必须是某种服务或 dao 类的一部分,该类在某处为 spring 声明。

有几种方法可以做到这一点,比如在 xml 中声明这些,或者使用 annotation-config 和 component-scan 设置正确的注释。

我可以推荐从头到尾阅读这篇很棒的article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-20
    • 2015-03-02
    • 2016-08-14
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多