Dear all,
I can reattach an individual object to a new session (with Lock or saveOrUpdate or merge) but that doesn't help my lazy-loaded sub collections. I get the dreaded
LazyInitializationException.
I know this topic has had lots of discussion but I have yet to find a satisfactory answer. I am already using the OpenSessionInView pattern, and this is solving half of my problems (it's a web-app environment. ZK actually) but I'm still having situations where an object persists between two web-requests (and so between two hibernate sessions) and so I need to 'refresh' and 'reattach' the objects reliably.
It's an AJAX web-app so there are lots of quicky satisfied requests (rather than the fewer, more slowly processed requests you'd find in a traditional webapp) and most of the objects I'm using need to be retained between requests. Many simple requests translates to many hibernate sessions, with most of the objects persisting between several database sessions.
Here's an example:
In one session I fetch an object (company) from the database and display it to the user. This object contains a list of subobjects (employees) that the user chooses to look at. He/she clicks on a button and requests that the list is expanded. Back on the server, we're now in a new session so the parent object is re-attached (saveOrUpdate) and then we try to loop through the list of subitems - only to get the LazyInitializationException. Here's some psudocode...
Code:
displayEmployees(Company company) {
Session ses = openNewSession();
ses.saveOrUpdate(company);
for (Employee emp : company.getEmployees()) {
displayEmployee(emp); //Throws Error!
}
}
Now, I
want to use lazy loading here because the sub list could be quite huge and will only be requested some of the time. I also don't want to leave the session hanging around between requests (while control is with the user) because we may be serving a hundred other users simultaneously and all these 'expensive' session objects are going to clog up the works. I understand long-lived sessions objects are frowned upon.
So, either i need to (some how) automatically cascade the ReAttaching process to subobjects and collections (is there a feature of Hibernate I'm missing here?), or manually re-attach collections before using them. Any clues?
Many thanks for your help,
Regards,
Ben.