【问题标题】:How to rollback hibernate operation when Exception occured after the operation?运行后发生异常时如何回滚休眠操作?
【发布时间】:2013-06-04 04:47:50
【问题描述】:

我有一个使用 spring+hibernate 创建的 java 应用程序。

我有这样的代码:

public class EmployeeDAO extends AbstractHibernateDAO {

    public void save(Employee emp) throws HibernateException {
        super.save(emp);    // inside this method, it calls hibernate session.save(). This super.save method can throws HibernateException
        doSometingElse(emp);    // inside this method, it doesn't call any hibernate methods. It can throws Exception too.
    }   
}

我想将 EmployeeDAO.save 方法作为事务视图中的原子方法。

如果 super.save(emp) 成功但 doSomethingElse(emp) 失败(通过抛出异常),那么我希望将员工记录插入 super.save (emp) 被回滚。

如何做到这一点?

【问题讨论】:

    标签: spring hibernate transactions atomic rollback


    【解决方案1】:

    您需要做的就是用@Transactional 像这样注释方法:

    public class EmployeeDAO extends AbstractHibernateDAO {
    
        @Transactional
        public void save(Employee emp) throws HibernateException {
            super.save(emp);    // inside this method, it calls hibernate session.save(). This super.save method can throws HibernateException
            doSometingElse(emp);    // inside this method, it doesn't call any hibernate methods. It can throws Exception too.
        }   
    }
    

    这样,如果在 EmployeeDAO save 中抛出异常,整个休眠操作的方法将被回滚。

    如果您希望此类中的所有方法都在它们自己的事务中运行,请改为注释类@Transactional

    您还需要确保配置了事务管理器。

    如果您使用 Spring Java 配置,您会希望事务管理器看起来像这样:

    @Bean
        public PlatformTransactionManager transactionManager() {
            JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());
            transactionManager.setDataSource(datasource());
            transactionManager.setJpaDialect(new HibernateJpaDialect());
            return transactionManager;
        }
    

    【讨论】:

    • 不知何故我没有做你的建议(使用@Transactional),它奏效了。我的事务管理器配置如下:<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> ...。你知道它是怎么工作的吗?
    • JPA 事务管理器只是一个更通用的事务管理器。您使用的休眠 3 仅适用于休眠 3。如果您使用的是休眠 4,您将使用休眠 4 事务管理器。 Here's a tutorial 向您展示如何使用 Spring 设置它们。另外,如果我的回答有效,您应该接受它。 :)
    • 您好,如果您阅读了我之前的评论,我完全没有听从您的建议。它已经在不更改任何配置的情况下工作。我确实在使用hibernate 3。我认为它之所以有效,是因为我正在使用TransactionInterceptor with key="save"。因此方法save隐含地成为事务。我真的很抱歉我在提问之前没有测试代码。要成为公平,我会要求结束这个问题。
    猜你喜欢
    • 2010-11-02
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2020-01-19
    • 2020-01-07
    • 2011-12-16
    相关资源
    最近更新 更多