代码之家  ›  专栏  ›  技术社区  ›  James

当发生未处理的异常时,Hibernate是否自动回滚编程事务?

  •  4
  • James  · 技术社区  · 15 年前

    方法(尽管代码很难看)来确保回滚,但我想知道是否有一种更优雅的方法来编码它,好吗?

    ApplicationContext ac = new ClassPathXmlApplicationContext("hibernate-config.xml");
    SessionFactory factory = (SessionFactory) ac.getBean("sessionFactory");
    Session session = factory.getCurrentSession();
    
    Transaction txn = null;
    try
    {
        txn = session.beginTransaction();
    
        // <insert transaction work here>
    
        txn.commit();
    }
    catch(Exception e)
    {
        try {txn.rollback(); }
        catch (Exception eAny) {  }
        throw(e);
    }
    finally { session.close(); }
    
    1 回复  |  直到 13 年前
        1
  •  0
  •   pihentagy    15 年前

    使用如何 Declarative Transaction Demarcation

    默认情况下,所有RuntimeException都会导致回滚,但您可以对其进行调优以回滚所有异常。

    好吧,你必须意识到一些问题,例如:你不能用 @Transactional ,仅bean的类或公共方法。