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

当发生未处理的异常时,Hibernate是否自动回滚编程事务?,hibernate,transactions,Hibernate,Transactions,在Hibernate中处理编程事务时,如果发生异常,是否需要显式调用回滚,或者如果存在未处理的异常,框架是否会负责调用回滚?下面的代码看起来像是确保回滚的安全的方法(尽管代码很难看),但我想知道是否有一种更优雅的编码方式 ApplicationContext ac = new ClassPathXmlApplicationContext("hibernate-config.xml"); SessionFactory factory = (SessionFactory) ac.getBean("s

在Hibernate中处理编程事务时,如果发生异常,是否需要显式调用回滚,或者如果存在未处理的异常,框架是否会负责调用回滚?下面的代码看起来像是确保回滚的安全的方法(尽管代码很难看),但我想知道是否有一种更优雅的编码方式

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(); }
ApplicationContext ac=new ClassPathXmlApplicationContext(“hibernate config.xml”);
SessionFactory=(SessionFactory)ac.getBean(“SessionFactory”);
Session Session=factory.getCurrentSession();
事务txn=null;
尝试
{
txn=session.beginTransaction();
// 
提交();
}
捕获(例外e)
{
请尝试{txn.rollback();}
捕获(异常eAny){}
投掷(e);
}
最后{session.close();}
如何使用

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

好吧,你必须知道一些问题,例如:你不能用
@Transactional
注释所有东西,只能用bean的类或公共方法