JPA equivalent command to Hibernate.initialize
Asked Answered
B

1

5

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?

Barkentine answered 31/3, 2015 at 12:21 Comment(0)
G
3

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.

Gorgeous answered 31/3, 2015 at 12:27 Comment(3)
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 alternativeBarkentine
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 betterGorgeous
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 @TransactionalEfthim

© 2022 - 2024 — McMap. All rights reserved.