1

我有一个使用 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)中插入的员工记录被回滚。

这个怎么做?

4

1 回答 1

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;
    }
于 2013-06-04T05:16:45.027 回答