2

I have a Lazy collection that I want to initialize at will in my service/controller. At this moment I can do:

Hibernate.initialize( myEntity.getListOfThings() );

This command is hibernate dependent and does not make the implementation of JPA transparent. Is there a JPA elegant way of doing this?

borjab
  • 9,420
  • 6
  • 58
  • 85

1 Answers1

2

No, there's no JPA equivalent. You can learn if the object is loaded and than use one of the two options, either accessing the properties while the object is still attached to persistence context, what I typically see is calling size, just for the sake of initializing the collection

myEntity.getListOfThings().size();

or use a query for initialization.

Community
  • 1
  • 1
Master Slave
  • 24,735
  • 4
  • 53
  • 54
  • Wouldn't hibernate return a proxy instead of the real object? When I try to access the object I think it is still attached to the persistence context but results a LazyInitializationException. You had my upvote but it would be helpfull if you could elaborate a bit the alternative – borjab Apr 01 '15 at 10:02
  • but I meant calling a property against a proxy object, if still attached that will fully initialize it. I've updated the answer to reflect it better – Master Slave Apr 01 '15 at 10:18
  • Why would I get `LazyInitializationException: failed to lazily initialize a collection of role: com.app.App.User.listOfThings, could not initialize proxy - no Session` ? I'm using Spring Data and I annotate my controller method with `@Transactional` – Radhwen May 21 '20 at 12:19