Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

Best way to override Hibernate's lazy loading in this instance

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).

Upvotes: 2

Views: 2462

Answers (2)

Bozho
Bozho

Reputation: 597106

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(..)

Upvotes: 2

skaffman
skaffman

Reputation: 403481

Using HQL, something like this:

from A as a
    inner join fetch a.b
    inner join fetch b.c

Upvotes: 1

Related Questions