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
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());
}