I do use OpenSessionInView for lazily loading objects in the same request. The problem that I've been running into is when objects loaded from Hibernate have lazily loaded collections and are put into the session before the collection gets used. Then on a future request, Hibernate tries to lazily load the objects and can't because the session used to retrieved them has been closed. So, I've been shying away from allowing Hibernate to lazily load things and have been using something similar to your CompanyDao.getEmployees(Company company) method. I can see both good and bad in this approach. I figure this is probably ok because it lets the web developer know that there is an extra request going to the backend to get that list, whereas lazily loading with Company.getEmployees() is a little too transparent and could easily be misused. But on the other hand, being able to have easy access to that data is very seductive.

The best solution I've found is to have all my backing beans that retrieve data be request scoped so that a) I always get the most recent data and b) I don't have to worry about any lazy loading issues like this. So, in this situation the only thing I really put into the session is the users profile and authetication information and some basic state information. Of course this does generate more hits on the database, but I'm willing to live with to a certain extent.

Ken Weiner wrote:

I have a question about designing a webapp to use a DAO layer, lazily loaded objects, Hibernate, and the OpenSessionInView technique.

Doesn't this strategy make it very difficult to reimplement the DAO layer sometime in the future? If you switched a DAO implementation from Hibernate to let's say, Spring JDBC, then how would all the lazy loading work? There would be no equivalent OpenSessionInView technique for Spring JDBC. For this reason, I have been shying away from designing my domain objects such that the rest of the app expects them to lazily load data.

So, instead of a Company class having a getEmployees() method, I would choose, instead, to have a CompanyDao.getEmployees(Company company) method that must be called at the point my webapp needs all the Employees for a Company.

Have any of you had the same concerns? Or am I missing how a webapp that relies on lazy-loaded object graphs can change DAO implementations easily?

-Ken


Reply via email to