views:

243

answers:

2

Suppose you have class B with lazily loaded property c. And that this is fine everywhere in the system except the following:

You have a class A with property b of class B. Whenever you load an entity of type A you want to load the full a.b.c chain non-lazily.

Is there a way to set up this type of logic in Hibernate?

Edit:
A property can also be defined with a formula that is a SQL expression. The documentation says:

A powerful feature is derived properties. These properties are by definition read-only. The property value is computed at load time. You declare the computation as an SQL expression. This then translates to a SELECT clause subquery in the SQL query that loads an instance:

<property name="totalPrice"
    formula="( SELECT SUM (li.quantity*p.price) FROM [...] )"/>

This would work if it was a Hibernate query that returned a Hibernate object.

Edit 2:
Other thoughts include declaring a class B2 which is exactly the same as B except it's C property isn't lazy loaded.

So far the options are:

  1. Rely on a query every time, as suggested by skaffman.
  2. Use a formula in a property to get fields I want, but no object.
  3. Create a B2 class with non lazy b.c. (kind of ugly).
+1  A: 

Using HQL, something like this:

from A as a
    inner join fetch a.b
    inner join fetch b.c
skaffman
For queries that's good. But if I traverse to a `.a` property of another object, I won't get `a.b.c` in one shot.
z5h
That';s true, but if you configure `B.c` to be lazily loaded, then that's how it's going to behave. If you want to override that, then you need to write your queries to explicitly fetch it.
skaffman
+1  A: 

If this is not a common case in your app (and it shouldn't be), you can manually initialize the dependent objects after fetching the A object, using Hibernate.initialize(..)

Bozho