在一个 session 中多次调用 beginTransaction 是否有风险?我的意思是例如:
session.beginTransaction();
session.saveOrUpdate(object1);
// .... some works
session.beginTransaction();
session.delete(object2);
// ... some other works
session.getTransaction.commit();
我这样做了,似乎没有问题(任何异常或警告)。事实上,我想知道当我以这种方式使用事务时会发生什么。
最佳答案
javadocs给个解释
beginTransaction()
Begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction. The class of the returned Transaction object is determined by the property hibernate.transaction_factory.
因此 - 它没有任何效果,它继续使用现有事务。所以不要这样做,因为它可能会让读者(包括你)感到困惑。如果您提交第一个事务然后开始第二个事务,则可以有多个事务。
关于java - Hibernate 中的多个事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992751/