开发者

Filter Lazily Initialized Hibernate Collection

开发者 https://www.devze.com 2023-01-19 03:30 出处:网络
This might be a super easy answer, since I\'m sure it\'s not uncommon.I see some similar questions, but nothing that seems to 开发者_如何学Godescribe my problem.

This might be a super easy answer, since I'm sure it's not uncommon. I see some similar questions, but nothing that seems to 开发者_如何学Godescribe my problem.

I have two objects: a car and person. They're in a many-to-many relationship, i.e. a car can be owned by multiple people, and a person can own multiple cars. Car has a lazily initialized set of Drivers:

@ManyToMany(targetEntity=Person.class, fetch=FetchType.LAZY)
private Set<Person> people;

I want to find all blue cars with owners under the age of 25:

Criteria foo = persistenceManager.createCriteria(Car.class, "myCarAlias");
Criteria bar = foo.createCriteria("drivers", "myDriverAlias");
//add restrictions on foo and bar for blue and age, respectively
baz = foo.list();

My problem is when I iterate through the list and call getDrivers() on each car, it initializes the collection and gets all of that car's drivers. I guess the .list() I ran doesn't set the results on each car.

I get back the results I expect if I manually run the SQL hibernate is generating, so I'm reasonably sure the criteria isn't the issue.

I can understand why this happens, but I'm not sure how to get around it without iterating over each car and running a query for drivers on each one. I'd like to avoid doing that if possible and would appreciate any advice.

Thanks in advance!


Were you hoping that the Drivers collection for each Car would only contain People who matched your criteria (i.e. are over 25)? In other words, you don't want the Drivers collection containing people who are over 25?

If that is the case then you will need to use a ResultTransformer (see section 15.4 of the Hibernate documentation) because Hibernate does not pre-filter collections before returning the results.

If however the problem is the Drivers collection is being lazy loaded and that is not desirable then setting the fetch mode (I typically use JOIN since IIRC FetchMode.EAGER was deprecated) should solve the problem:

baz = persistenceManager.createCriteria(Car.class, "myCarAlias")
    .setFetchMode("drivers", FetchMode.JOIN)
    // add additional restrictions here
    .list();


section 15.5 of the hibernate documentation. Basically you can set the fetch strategy for your criteria queries, which should take precedence over the basic fetch strategy you have defined for the relationship.

the example from the documentation

List cats = sess.createCriteria(Cat.class)
   .add( Restrictions.like("name", "Fritz%") )
   .setFetchMode("mate", FetchMode.EAGER)
   .setFetchMode("kittens", FetchMode.EAGER)
   .list();

and the documentation http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html

0

精彩评论

暂无评论...
验证码 换一张
取 消