Why is Hibernate Open Session in View considered a bad practice?

HeDinges picture HeDinges · Jul 9, 2009 · Viewed 62.3k times · Source

And what kind of alternative strategies do you use for avoiding LazyLoadExceptions?

I do understand that open session in view has issues with:

  • Layered applications running in different jvm's
  • Transactions are committed only at the end, and most probably you would like the results before.

But, if you know that your application is running on a single vm, why not ease your pain by using an open session in view strategy?

Answer

Robert Munteanu picture Robert Munteanu · Jul 9, 2009

Because sending possibly uninitialised Proxies, especially collections, in the view layer and triggering hibernate loading from there can be troubling from both a performance and understanding point of view.

Understanding:

Using OSIV 'pollutes' the view layer with concerns related to the data access layer.

The view layer is not prepare to handle a HibernateException which may happen when lazy loading, but presumably the data access layer is.

Performance:

OSIV tends to tug proper entity loading under the carpet - you tend not to notice that your collections or entities are lazily initialised ( perhaps N+1 ). More convenience, less control.


Update: see The OpenSessionInView antipattern for a larger discussion regarding this subject. The author lists three important points:

  1. each lazy initialization will get you a query meaning each entity will need N + 1 queries, where N is the number of lazy associations. If your screen presents tabular data, reading Hibernate’s log is a big hint that you do not do as you should
  2. this completely defeats layered architecture, since you sully your nails with DB in the presentation layer. This is a conceptual con, so I could live with it but there is a corollary
  3. last but not least, if an exception occurs while fetching the session, it will occur during the writing of the page: you cannot present a clean error page to the user and the only thing you can do is write an error message in the body