Is there some easy way to fetch all associat开发者_开发技巧ions of a big object graph without having to 'left join fetch' all of them? Can't I just tell Hibernate to fetch associations eager by default?
Even if it is possible to have a global lazy=false
(google is not showing it, but it might be possible) you really don't want to do this. Do you really want to load the entire db, or a significant object graph, for every request? Keep in mind, the way hibernate works, it needs to instantiate every object in the graph. Its going to be slow and memory intensive, and will probably crash your app as your data grows.
If you must load a large set of data, use a custom hql query, and pull the fields you need out of the tables. Avoid the object instantiation. Also, you could let the db do a lot of the heavy lifting by using a view; i.e. let the db continously update a virtual table dynamically, so you only need to select a single table from the web-apps perspective.
Another option is to rework your interactions so you don't have to do this in the first place.
You can put it into the hibernate-mapping tag:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
But you won't get happy with it.
By the way: eager loading and join fetch are different concepts! Both aren't silver bullets to avoid any kind of problem.
- Generally using eager loading may case a heavy N+1 problem
- Generally using join fetch may cause heavy multiplication of results.
Use both where it is appropriate - and avoid both if in doubt.
See these related blog posts by Ayende Rahien:
- NHibernate is lazy, just live with it
- The Stripper Pattern
I am not aware of a global switch either. Controlling fetching with annotations works, though.
@Proxy(lazy = false)
public class SomeBean {
...
@ManyToOne(fetch = FetchType.EAGER)
private OtherBean otherbean;
...
}
In HQL you need to specify you want to eagerly fetch an association.
Regardless, as @hvgotcodes stated above, trying to eagerly fetch everything quickly leads to performance issues. You will most likely find yourself fetching large portions of the DB when trying to do so.
I suggest you read the Fetching Strategies in the hibernate manual to get the hairy details.
精彩评论