且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在视图中的Hibernate Open Session被认为是不好的做法?

更新时间:2022-11-16 12:46:36

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