0

I have a class of User that has a list (collection) of Projects:

@OneToMany(mappedBy = "user_owner_id")
private Collection<Project> project = new ArrayList<>();

And at some point, I want to see the list of projects and I fetch them:

Session sessionF = sessionFactory.openSession();
sessionF.beginTransaction();        
user = sessionF.get(User.class, user.getId());
sessionF.getTransaction().commit();
List<Project> projects = (List<Project>) user.getProject();     
sessionF.close();

If I don't do something with projects it throws the error: org.hibernate.LazyInitializationException: could not initialize proxy – no Session

But if I am adding a int projectCount = projects.size(); it works just fine. Why does that happen and how can I resolve it without playing with projects here?

P.S. After I am closing the session I am just passing it through the HttpServletRequest and then going with a for loop over it in a jsp file.

2
  • 1
    In the first case, the lazy association is never loaded while the session is opened, but you try to load it after the session is closed, so there is no way to get the data out of the database anymore, hence the exception. In the second case, you load the lazy collection while the session is still opened, so it's still there in memoruy once it's closed. Commented Sep 7, 2019 at 21:47
  • Shouldn't the user.getProject() load it to the List<Project> projects? This is the part where I am confused. Why do the projects.size() load it then? Commented Sep 7, 2019 at 22:31

1 Answer 1

1

Check Fetching Strategies section of Hibernate Reference Documentation

Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)

Returning your collection from an entity and assigning it to a variable does not involve calling a method on that collection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.