We are trying to implement a simple model of hierarchical data, which is as follows.
public class Team {
/* ... */
@OneToMany(fetch = FetchType.LAZY, mappedBy = "team")
protected List<Member> members;
}
public class Member {
/* ... */
@ManyToOne(fetch = FetchType.LAZY)
protected Team team;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "member")
protected List<Assignment> assignments;
}
public class Assigment {
/* ... */
@ManyToOne(fetch = FetchType.LAZY)
protected Member member;
}
The idea behind the mapping is quite straightforward - a team is composed of members, who are in turn assigned some duties.
Problem: creating a query which will return the hierarchy of team->member->assignment with conditions imposed on assignments (e.g. deadline in < 1 week).
Solutions so far:
- Querying for all Team entities and iterating over two-level collections in a transaction, filtering out those assignments, which do not fall into time range. Pros: simple. Cons: possible large overhead.
Following query:
SELECT t FROM Team t left join fetch t.members m left join fetch m.assignments
Unfortunately, the query fails even without the any condition for assigment filtering, throwing:
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
I don't understand why it does not allow simultaneous fetching on two relations, as a similar example is shown in Hibernate docs:
from Cat as cat
inner join fetch cat.mate
left join fetch cat.kittens child
left join fetch child.kittens
Questions:
- Is it possible to fetch the whole tree-like collection with filtered leaf-level (assignments) with a single SQL statement? If not, what could be improved in the proposed solution?
- Why the double fetch does not work properly?
Additional info: we're using Hibernate 4.3.5.FINAL & PostgreSQL.