Kiva
Kiva

Reputation: 9353

Hibernate get object with linked objects

I have a problem with my hibernate mapping and queries. I have an object A which have a relation with B and C.

The fetch mode is lazy (@ManyToOne(fetch = FetchType.LAZY)) and I can't change it. So my problem is next:

When I get an object by the get method (hibernateDao.get), I get the object A whitout relation with B and C.

If I create a criteria, I force the relation with criteria.setFetchMode(...) to get all with only query. But I have read on the web what it's not a good thing to make a criteria to get an object by primary key.

How to do this with the method get ?

Thanks.

Upvotes: 2

Views: 3625

Answers (2)

Renan
Renan

Reputation: 741

Call Hibernate.initialize();

Example:

myEntity = hibernateDao.get...;
Hibernate.initialize(myEntity);

This will force hibernate to load all mapped entities in myEntity.

Upvotes: 0

jpkroehling
jpkroehling

Reputation: 14061

You can use Fetch Profiles to have the fetch mode set as Lazy as default, and as Eager for a specific query: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e3524

And if you are using a Hibernate version which doesn't supports Fetch Profiles, you can always do a HQL query which retrieves the tree you need, using joins.

But I have read on the web what it's not a good thing to make a criteria to get an object by primary key.

I would be very careful before ruling out a solution just because you read somewhere that it's "bad". It may be a bad thing in the end, but if you don't understand why this is bad, you may be ruling out a solution which was made for your specific case ;-)

Upvotes: 2

Related Questions