Few facts regarding the setup:
- It’s a Tomcat based app (althoug the issues arise outside Tomcat’s context as well – JUNIT)
- Not using Spring
- Every thread has its own Hibernate
Session(at TLS) - Objects are being saved/loaded in a mixed way, i.e
ObjAmay be created by thread A and later be manipulated by thread B and even later be updated by thread A and yet again be manipulated by thread Z but this time using HQL!
Having the above setup I’m getting errors such as:
org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessionsorg.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
My understanding is that
- It’s all related to Hibernate’s
Session, being that a session “owns” the objects “attached” to it (those it created/loaded) - AND POSSIBLY an issue of caching
The question is obvious:
- Am I understanding the core issue (above)?
- How do I avoid such issues?
- Is there a rule of thumb that would help avoid these issues?
- Would using Spring help solving it (be a bit specific about it please)?
- Would detaching from
Sessionevery object after fetching it from the datastore, and attaching it to aSessionlater just before updating it would be the ideal way to handle it?
I could of course avoid all of it if I’d use only one Session object but that sounds so… blocking (thread-wise).
I’m sure these sort of issues were solved long time ago, just need to find it (without re-inventing the wheel).
Calling
clear()before fetching the object(s).