views:

180

answers:

1

There are times when I want to define a relationship as being lazily loaded, since 90% of the time I don't want the child entities, yet also have the possibility of getting the whole hierarchy at once, under certain circumstances. I don't want to achieve this by using a named query, since the parent-child hierarchy is useful when I convert to e.g. JSON format. At the moment my dirty hack is to call .getChildEntities().size() to force the lazy load within the same transaction.

Is there a better way?

+2  A: 

Depends on the JPA implementation of course. Some (most) will load all with that method invocation you quote, but some could issue a COUNT(*) query to get the size also for reasons of memory management (not wanting to load all elements for cases where there are many)

--Andy (DataNucleus)

DataNucleus
thanks for your comment, Andy. I'm aware that my workaround may not always work with all implementations (that's why it's a hack:)). But, surely, there must be a standard way to load the child entities. I could iterate through them, making a redundant call to the primary key value, but that's not exactly elegant...
davek
There is no standard way sadly. The idea is the persistence implementation gets you the data when you need it, so you give over control, just saying "lazily load it". Doesn't your impl get you the data efficiently ? Aren't all elements there ?
DataNucleus
Yes, my implementation gets me all the data I need, but calling a property (which I then don't directly use) on an entity for no other reason than to force lazy loading just doesn't seem "right". I'm happy for the implementation to give me the data when I want it, but if I happen to have moved on to a different transaction then it complains.
davek
With JPA the problem is that there is no way of defining a different "fetch group" for use at detach than at instantiation, so the only way of forcing load is to touch the field as you are doing. With JDO you can have a fetch group that you enable before detach meaning that the field is loaded when detached, resulting in no need to "touch" it. Doesn't help your case, just for interest
DataNucleus
many thanks for the background info: at least I know I'm not missing anything obvious!
davek