In Spring with jpa/hibernate, how do I keep a session open to avoid lazy initialization exceptions?

前端 未结 6 1596
温柔的废话
温柔的废话 2020-12-02 14:52

I currently mark collections in entity beans as eager to avoid getting a lazy initialization exception when I try to access the collection properties after loading the bean

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 15:23

    As others have said, you should read up on "open session in view" pattern, the basic idea of which is to have a hibernate session open for the full duration of processing http request. There are both hibernate specific and spring solutions - I used spring's before and it works fine.

    In the question you mention that you don't want to have transaction open for a long time. For most of the people this is not an issue because each request is processed relatively quickly. However if in your case it is indeed impossible this pattern will not work for you. Can you elaborate on why you don't want the transactions kept open?

提交回复
热议问题