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 describe 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!