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

后端 未结 9 2162
轮回少年
轮回少年 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

    If you're using an Inversion of Control (IoC) container such as Spring, you may want to read up on bean scoping. Essentially, I'm telling Spring to give me a Hibernate Session object whose life cycle spans the entire request (i.e., it gets created and destroyed at the start and end of the HTTP request). I don't have to worry about LazyLoadExceptions nor closing the session since the IoC container manages that for me.

    As mentioned, you will have to think about N+1 SELECT performance issues. You can always configure your Hibernate entity afterwards to do eager join loading in places where performance is an issue.

    The bean scoping solution is not a Spring-specific. I know PicoContainer offers the same capability and I'm sure other mature IoC containers offer something similar.

提交回复
热议问题