failed to lazily initialize a collection of role,..could not initialize proxy - no Session - JPA + SPRING

前端 未结 4 1473
耶瑟儿~
耶瑟儿~ 2021-02-02 14:58

I am using JPA(with Hibernate 4.3.3 as persistence provider ) along Spring (3.2.2) , all my fields are loading fine but when I am trying to access my Collection it\'s throwing t

4条回答
  •  花落未央
    2021-02-02 15:27

    The problem is that when this method call returns:

    Category parentCategory=serviceCategory.findCategoryById(2l);
    

    Here you are no longer in a @Transactional context. this means that the session linked to parentCategory got closed. now when you try to access a collection linked to a closed session, the No Session error occurs.

    One thing to notice is that the main method runs outside any spring bean and has no notion of persistence context.

    The solution is to call the parentCategory.getAllParentCategoryrefs() from a transactional context, which can never be the main method of your application.

    Then reattach the parentCategory to the new persistence context, and then call the getter.

    Try for example to pass the parentCategory back to a transactional method of the same service:

    serviceCategory.nowItWorks(parentCategory);
    

    where the method on the service is transactional:

    @Transactional(readOnly=true)
    public void nowItWorks(Category category) {
        dao.nowItWorks(category);
    }
    

    And in the DAO:

    public void nowItWorks(Category category) {
        Category reattached = em.merge(category);
        System.out.println("It works: " + reattached.getAllParentCategoryrefs());
    }
    

提交回复
热议问题