我正在使用Hibernate(4.1.8.FINAL),MySQL(InnoDB),我遇到了保存多个实体的问题。Hibernate 4.1.8.FINAL支持交易:是或否?
根据Hibernate文档http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch15.html批处理应予以支持,但我得到以下异常:
org.hibernate.TransactionException: nested transactions not supported
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:152)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1395)
...
这是我写的代码(类EntryDaoImpl.java):
@Transaction
public void saveAll(final Collection<T> entities) {
if (CollectionUtils.isEmpty(entities)) {
return;
}
final Session session = this.sessionFactory.getCurrentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
for (final T entity : entities) {
session.saveOrUpdate(entity);
}
tx.commit();
} catch (final RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.flush();
session.clear();
}
}
而且这里是JUnit方法:
@Test
public void deleteAddress() {
Entry entry;
// Entry 2 has three addresses (delete all those)
entry = this.entryDao.findById(2);
Assert.assertEquals(3, entry.getAddresses().size());
entry.setAddresses(null);
this.entryDao.saveAll(Collections.singleton(entry));
}
exc如果只更新一个实体,也会发生冲突。我也试过用的openSession()代替的getCurrentSession(),但例外是以下几点:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.internal.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:638)
at org.hibernate.event.internal.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:65)
如果我去没有事务逻辑,那么它的工作原理。在研究搜索引擎的过程中,我发现许多开发人员告诉Hibernate根本不支持事务。不确定这个陈述是否过时。 困惑
所以我的问题是:Hibernate是否支持事务(如文档中所述)?和/或者你能告诉我我的代码有什么问题吗?谢谢:-)
@Transaction注释来自哪里?你使用spring并且意味着@Transactional?或者另一个声明式交易系统?如果是,让它处理事务 - 异常消息表明你试图在另一个事务中开始一个事务(“嵌套”)。很可能是因为你从hibernate会话手动打开了一个事务,而声明式事务系统已经打开了一个事务。 – Pyranja