0

Suppose I have a Post class which has a PostComment collection, and that I load Post. PostComment has lazy="true" set, so PostComment is now represented by an Hibernate Proxy.

If I load Post in a session, let's call it session1, and then I close session1 before accessing PostComment, how can I access PostComment from a second session opened later?

I tried to access PostComment from session2 but got LazyInizializationException, I believed that to enable lazy loading it was enough to have a session opened, not the same session which loaded the parent object.

Should I use session2.update() to attach the objects to session2? Are there other methods other than using the same session in the whole process?

cdarwin
  • 4,141
  • 9
  • 42
  • 66

1 Answers1

1

You can either reattach the object to a new session as you've described in your post or instead disable lazy initialization by using FetchType.EAGER as your fetch type i.e.:

@OneToMany(fetch = FetchType.EAGER)
private Map<String, Attribute> attributes = new HashMap<String, Attribute>();

See this post for more info about the differences between lazy and eager fetching: Difference between FetchType LAZY and EAGER in Java Persistence API?

whitebrow
  • 2,015
  • 21
  • 24