I am using Hibernate (4.1.8.FINAL), MySQL (InnoDB) and I am experiencing a problem with saving multiple entities.
According to Hibernate documentation http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch15.html the batch processing should be supported, but I am getting following exception:
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)
...
Here’s the code I wrote (Class 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();
}
}
And here is the JUnit method:
@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));
}
The exception also occurs if only one entity will be updated. I also tried with openSession() instead of getCurrentSession() but the exception would be following:
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)
If I go without transaction logic then it works. During research with search engine I see many developers told that Hibernate doesn’t support transaction at all. Not sure if this statement is outdated. confused
So my question is: does Hibernate supports transaction (as described in documentation)? And/or can you tell me what is wrong with my code? Thank you 🙂
You are using both declarative transaction (@Transaction) as well as programatic transaction.
Since you are using both the transaction in the same code, Hibernate complains
Remove your
Transactionannotation at the top of your class and it should work, else remove yourbeginTransactionandcommit.Hope it helps.