Reputation: 1283
I have two threads, A and B, and each of them inserts data into two different and unrelated tables.
However I am getting an org.hibernate.TransactionException: nested transactions not supported
.
Here is the code doing the insertion for thread A :
@Override
public void setA(List<A> a) throws HibernateException {
if (session == null) {
session = sessionFactory.openSession();
}
Transaction tx = session.beginTransaction();
try {
int count = 0;
for (A row : a) {
session.save(row);
if (count++ % 1000 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}
}
The other method called by thread B is similar, only it is setting Bs instead of As...
How do I get these 2 threads to run concurrently without this exception ?
Upvotes: 0
Views: 442
Reputation: 16638
You must use synchronized
block or synchronized method
to perform above task.
Note, that Session is not a thread-safe object, but if you're sure it won't have problems with concurrency, what you need is just to use TransactionSynchronizationUtils
to bind a session to the thread resources and then unbind it when desired
Upvotes: 1