考虑以下简单的Hibernate场景:
session = getHibernateSession(); tx = session.beginTransaction(); SomeObject o = (SomeObject) session.get(SomeObject.class, objectId); tx.commit();
此代码产生以下异常:
org.hibernate.TransactionException: Transaction not successfully started at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:100) at com.bigco.package.Clazz.getSomeData(Clazz.java:1234)
这是怎么回事?
好吧,看来一旦我们达到要求tx.commit(),交易就已经提交了。我唯一的猜测是Hibernate get()在访问对象时已经提交了事务。
tx.commit()
get()
解决方法很简单:
// commit only if tx still hasn't been committed yet (by hibernate) if (!tx.wasCommitted()) tx.commit();