为什么在视图中的Hibernate Open Session被认为是不好的做法? [英] Why is Hibernate Open Session in View considered a bad practice?

查看:122
本文介绍了为什么在视图中的Hibernate Open Session被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我明白视图中的开放会话存在以下问题:




  • 分层应用程序运行在不同的jvm中
  • 事务仅在最后提交,很可能您希望以前的结果。但是,如果您知道您的应用程序正在单个虚拟机上运行,​​那么为什么不通过在视图中使用打开的会话来缓解您的痛苦呢?因为在视图层发送可能未初始化的代理,尤其是集合,并从那里触发hibernate加载可能会有麻烦理解:



    使用OSIV '污染'了与数据访问层有关的视图层。



    视图层不准备处理 Hibernate例外情况这可能会发生在延迟加载时,但可能是数据访问层。



    性能



    OSIV倾向于在地毯下拖曳适当的实体加载 - 您往往不会注意到您的收藏或实体是懒惰地初始化的(可能是N + 1)。更方便,更少控制。

    /blog.frankel.ch/the-opensessioninview-antipatternrel =noreferrer> OpenSessionInView反模式有关此主题的更多讨论。作者列出了三个要点:每一个延迟初始化都会得到一个查询,意味着每个实体都需要N个元素+1查询,其中N是惰性关联的数量。如果你的屏幕显示表格数据,阅读Hibernate的日志是一个很大的暗示,你不应该这样做,因为你应该在表现层中用数据库玷污你的指甲,这完全不符合分层结构。
  • 。这是一个概念性的概念,所以我可以忍受它,但最后但并非最不重要的是,如果在获取会话时发生异常,它将在写入页面:您无法向用户展示干净的错误页面,您唯一可以做的就是在主体中写入错误消息



    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?

    解决方案

    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

    这篇关于为什么在视图中的Hibernate Open Session被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆