Tuesday, July 29, 2014

Hibernate: Illegal attempt to associate a collection with two open sessions

I got this error when I try to update multiple times. My case is a student tries to enroll multiple classes. My data access object (called KelasDAO) only support a student enrolling a single class. So I use a loop to go through the collection and add each class by calling the method. And this error occurred.

It took me a while to figure this out but this is what I have in mind (after a few minutes of googling): Each time  I call the DAO functions, it gets a hibernate session and use that session to update the object. Since I called the function multiple times, I have many sessions each trying to update the same object. Hibernate does not allow this: a single object cannot be updated by two or more sessions. The reason is hibernate does not directly update the object, but put it on transient mode until the database server notify that the update is a success.

How do I solve it? There's a quick solution to use merge() instead of update(). It works but I don't like the idea. This Method merge() will merge the transient objects and I don't know what happened after that.

Another solution (although I haven't tried it yet) is to move the loop to DAO and use the same session to update. So instead of using:

for each object
  DAOtoUpdate(Object obj);

and in the DAOtoUpdate() method:



DAOtoUpdate(Collection col);

and in the DAOtoUpdate() method:

for each object in collection

Please be noticed I haven't tried it yet. Feel free to try :)

No comments: