0

I need to do some processing on an Entity. I'd like it to be outside a transaction. The thing is this entity contains some lazy-loaded fields so that my program fails on accessing some of them because of not having a session active.

The most natural thing to do would be to fully initialize such entity once it's loaded but still in transactional scope (before detaching it). But I can't find how to do that. Is there really no simple method do such a trivial thing? I'd like to stay behind JPA spec.

For some reason fetch all properties in jpql does not work.

kboom
  • 2,279
  • 3
  • 28
  • 43

1 Answers1

1

Just call a method on the lazy proxies you want to initialize:

SomeEntity e = ...;
e.getFoos().size(); // now foos is initialized
e.getBar().getName(); // now bar is initialized

To load the whole state at once using JPQL, you need to use fetch joins:

select e from SomeEntity e
left join fetch e.foos
left join fetch e.bar
where ...
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • The second option would be a way to go for me (even if I had to list about a dozen highly nested properties...) except its not working for some reason - fields still are PersistentSets which aren't loaded (and accessing them results in exception - "no session"). Do it have something to do with cascade options? I did not define any on those fields. – kboom Mar 08 '14 at 16:47
  • Check the generated SQL. It should work fine, even if the spec only says that fetch is a "hint". But nothing forbids you to use fetch joins, and to make sure everything is loaded using the first technique. Anyway, it's impossible to diagnose anything without seeing a single line of code and a precise description of the problem. – JB Nizet Mar 08 '14 at 16:52
  • I'm sorry, you're right. It's working now. The thing was I was using two queries and I edited the wrong one. I guess there is no easier method to do what I wanted to do. Thanks! – kboom Mar 08 '14 at 17:34