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

后端 未结 9 2077
轮回少年
轮回少年 2020-11-22 17:08

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

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

  • Layered
相关标签:
9条回答
  • 2020-11-22 17:45

    In my own experience, OSIV is not so bad. The only arrangement I made is using two different transactions: - the first, opened in "service layer", where I have the "business logic" - the second opened just before the view rendering

    0 讨论(0)
  • 2020-11-22 17:47
    • transactions can be committed in the service layer - transactions are not related to OSIV. It's the Session that stays open, not a transaction - running.

    • if your application layers are spread across multiple machines, then you pretty much can't use OSIV - you have to initialize everything you need before sending the object over the wire.

    • OSIV is a nice and transparent (i.e. - none of your code is aware that it happens) way to make use of the performance benefits of lazy loading

    0 讨论(0)
  • 2020-11-22 17:48

    I wouldn't say that Open Session In View is considered a bad practice; what gives you that impression?

    Open-Session-In-View is a simple approach to handling sessions with Hibernate. Because it's simple, it's sometimes simplistic. If you need fine-grained control over your transactions, such as having multiple transactions in a request, Open-Session-In-View is not always a good approach.

    As others have pointed out, there are some trade-offs to OSIV -- you're much more prone to the N+1 problem because you're less likely to realize what transactions you're kicking off. At the same time, it means you don't need to change your service layer to adapt to minor changes in your view.

    0 讨论(0)
提交回复
热议问题