Hibernate Lazy using Initilize or EAGER loading
I have three tables,
users
user_associations
association_type.
User开发者_如何学运维s are associated to each other through the users_associations table and then the association is given a type such as PARENT, or FRIEND, etc..
When I call my view I have the table data for user's associations to each other. Within each list there is a relationship to the current users data, the associated users data, and the list of association types.
I am using Hibernate and I am confused between EAGER fetching the data and LAZY loading it. When I call my DAO it looks like this
List<UsersAssoc> assoc = (List<UsersAssoc>)session.getNamedQuery("UsersAssoc.getAssoc").setInteger("id", id).list();
To get LAZY loading to work I have to call Hibernate.initialize on all of the sub objects
for(UserAssoc a : assoc ) {
Hibernate.initialize(a.getUser() );
Hibernate.initialize(a.getAssocTypes() );
Hibernate.initialize(a.getAssociatedUser() );
}
I need to refer to all of the data in my view and I am trying to do it without storing all of it in memory. Which option is the best? Eagerly load it or Initialize each type within Hibernate. This might not even be the right way of doing it. I need some direction. Thanks
lazy describes whether collections are loaded immediately -- so if you have lazy=false hibernate will by default load the collection when you load the parent. It is a mapping attribute.
when using hql, your fetching strategy overrides the setting in your mapping. From the documentation:
"A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 19.1, “Fetching strategies” for more information."
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html
It is common to have all your mapping be lazy false, but to have specialized hql based DAO methods so you can get at your data in specific ways for specific cases.
精彩评论