I was wondering how you guys would do this. I'm new to hibernate and trying to come up with the best fetching strategy.
I have a number of instances where an entity has two or more many to many relationships to other entities. I have a User who is related to many Locations, and belongs to many Roles. I'm fetching the data for a SWING application which will also display the entire list of Roles and Locations, so I've already select *'d them.
My first question is:
Does it make sense to do one outer join fetch, and then iterate the results to get the other?
ie:
List users = session.find("from User as u left join fetch u.Locations");
if ((users != null) && (users.size() > 0)) {
HashSet distinctUsers = new HashSet(users);
Iterator i = distinctUsers.iterator();
while (i.hasNext()) {
User user = (User)i.next();
Hibernate.initialize(user.getRoles());
}
data.setUsers(new ArrayList(distinctUsers));
}
Or.. would it be better to do two outer joins and return one of the resulting lists (I'm only assuming this would work, since the session-level cache would likely retain the previously fetched collections of Locations.
ie:
List users = session.find("from User as u left join fetch u.Locations");
List usersAndMore = session.find("from User as u left join fetch u.Roles");
HashSet distinctUsers = new HashSet(usersAndMore);
data.setUsers(distinctUsers);
Thoughts? The users table is going to hold something in the order of 100-200 users, each with maybe between 0-10 Locations and 0-10 Roles. Are either of these patterns feasible? Why would you choose one over the other. I'm like the second one, but I'm kind of bugged by how unreadable it might be to someone who didn't know why I was doing that.
A related question... My queries to select all Locations and Roles are always hitting the database, despite being set up to cache. I can guess why this would be, but is there a way to make use of the cache for them?
thanks in advance.
phill
|