org.hibernate.LazyInitializationException: How to properly use Hibernate's lazy loading feature

前端 未结 3 1017
名媛妹妹
名媛妹妹 2020-12-05 16:27

I got some trouble loading a list of objects from my database using Hibernate and lazy=true mode. Hope that someone can help me out here.

I have a simple class here

3条回答
  •  醉酒成梦
    2020-12-05 16:58

    You need to wrap your entire process within a transaction.

    So instead of starting and commiting the transaction in loadUserAccount, do it outside of that.

    For example:

    public void processAccount()
    {
        getSession().beginTransaction();
        UserAccount userAccount = loadUserAccount("User");
        Vector accts = userAccount.getMailAccounts();  //This here is lazy-loaded -- DB requests will happen here
        getSession().getTransaction().commit();
    }
    

    Usually, you want to wrap your transaction around the entire unit of work. I suspect that your understanding of transactions is a little too fine grained.

提交回复
热议问题