Hi,
I have a one-to-many relationship as described in [url]http://forum.hibernate.org/viewtopic.php?p=2177261#2177261
[/url]
I want to fetch all Departments for a location. I do this by
Code:
public Collection findByLocation(String location){
ArrayList departments = new ArrayList();
Session session = null;
try {
session = sf.openSession();
Query q = session.createQuery("from Department as dep where dep.location = :location");
q.setParameter("location",location);
for(Iterator i = q.list().iterator();i.hasNext();) {
departments.add((Department)i.next());
}
} catch (Exception e) {
System.out.println("Error in findByLocation " + e.getMessage());
e.printStackTrace();
} finally {
try {
session.close();
} catch (Exception e) {
System.out.println("Hibernate Exception " + e.getMessage());
e.printStackTrace();
}
}
return departments;
}
This fires 2 queries on the database
- first query to fetch all departments for this location
- second query to fetch all employees for the above departments
How do I make hibernate join these to queries into one? When I try
Code:
Query q = session.createQuery("from Department as dep left outer join fetch dep.employees where dep.location = :location");
Hibernate returns duplicate rows (obviously)!
Even if I try
Code:
Query q = session.createQuery("select dep from Department as dep left outer join fetch dep.employees where dep.location = :location");
I cannot avoid duplicates.
What am I doing wrong?