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.
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 ;-)
Call Hibernate.initialize();
Example:
myEntity = hibernateDao.get...;
Hibernate.initialize(myEntity);
This will force hibernate to load all mapped entities in myEntity
.
精彩评论