Issue
So i was trying to implement proper multithreading for saving and update operation in hibernate. Each of my threads uses one newly created session with its own transaction.
I always get a "Illegal attempt to associate a collection with two open session" exception, because im using multiple sessions at the same time ( I also tested it with a shared one, did not worked either ). The problem here is that i need multiple sessions, thats the way i was told hibernate multithreading would work.
This code basically gets executed on multiple threads at the "same" time.
var session = database.openSession(); // sessionFactory.openSession()
session.beginTransaction();
try {
// Save my entities
for (var identity : identities)
session.update(identity);
session.flush();
session.clear();
session.getTransaction().commit();
} catch (Exception e){
GameExtension.getInstance().trace("Save");
GameExtension.getInstance().trace(e.getMessage());
session.getTransaction().rollback();
}
session.close();
So how do i solve this issue ? How do i keep multiple sessions and prevent that exception at the same time ?
Solution
The issue you are facing is that you load an entity with a collection with session 1 and then somehow this object is passed to session 2 while the object is still associated to an open session 1. This simply does not work, even in a single threaded environment.
Either detach the object from the session 1 or reload the object in session 2.
Answered By - Christian Beikov
Answer Checked By - Willingham (JavaFixing Volunteer)