I'm seeing something unexpected and I 'd like to determine if I'm doing something wrong, or if there's a logical reason for the behavior. When I map a parent child relationship like so:
Code:
public class ItemA {
@OneToMany(fetch = FetchType.EAGER)
private Set<ItemB> itemBs = new HashSet<ItemB>();
...
}
and then retrieve a list of ItemA's with something like
Code:
session.createQuery("from ItemA").list();
everything works as expected. The ItemA's and the child ItemB's are retrieved with one query using a left outer join. Great. That's what I want. However, when I map something similar like:
Code:
public class ItemA {
@CollectionOfElements(fetch = FetchType.EAGER)
private Set<String> strings = new HashSet<String>();
...
}
and then retrieve a list of ItemA's using the same statement as above, I get one query to retrieve the ItemA's and then another query for each ItemA retrieved to get the ItemB's, which quickly leads to an n+1 issue with this particular object (a frequently retrieved object where the ItemB's in question are always needed). What's odd though, is that if I retrieve only one ItemA, then a single query is used with a left outer join to retrieve the ItemB's; just as one would expect.
Am I missing a second annotation or attribute that would make the @CollectionOfElements retrieve ItemA's with one query or is there a reason why this is a bad idea with @CollectionOfElements as compared to @OneToMany?
Hibernate version:
Hibernate-core 3.2.2ga
Hibernate-annotations 3.2.1ga
Name and version of the database you are using:
HSQL to reproduce these tests, although the same behavior appears in PostgreSQL.