java – 为什么Hibernate Open Session in View被认为是一种不好的做法?
作者:互联网
您使用什么样的替代策略来避免LazyLoadExceptions?
我确实理解在视图中打开会话有以下问题:
>分层应用程序在不同的jvm中运行
>事务只在最后提交,很可能你以前想要结果.
但是,如果您知道您的应用程序在单个虚拟机上运行,为什么不通过在视图策略中使用开放会话来减轻您的痛苦?
解决方法:
因为在视图层中发送可能未初始化的代理(尤其是集合)并从中触发休眠加载可能会从性能和理解的角度来解决问题.
理解:
使用OSIV“污染”视图层,其中涉及与数据访问层相关的问题.
视图层不准备处理延迟加载时可能发生的HibernateException,但可能是数据访问层.
性能:
OSIV倾向于在地毯下拖拽适当的实体加载 – 您往往没有注意到您的集合或实体被懒惰地初始化(可能是N 1).更方便,更少控制.
更新:有关此主题的更多讨论,请参阅The OpenSessionInView antipattern.作者列出了三个要点:
- 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
- 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
- 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
标签:java,jpa,hibernate,lazy-loading,open-session-in-view 来源: https://codeday.me/bug/20190911/1804433.html