tags:

views:

31

answers:

1
public class Case
{
    public int Id { get; set; }
    public string Number { get; set; }
    public Employee Employee { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string EmployerIdentifier { get; set; }
    public Case Case { get; set; }
}

There is a one to one releationship between Case and Employee. However there are multiple records in the DB that represent the same Employee. To find those records we look at the EmployerIdentifier. So if I have only the Employee.Id how can I write an NHibernate query that returns all the cases for that Employee. In SQL I would do it by joining to the employee table twice (see example below).

Declare @TargetEmployeeID bigint
set @TargetEmployeeID = 246834
select * from Cases C
inner join Employees E on E.EmployeeID = C.EmployeeID
inner join Employees EST on EST.EmployerIdentifier = E.EmployerIdentifier
where EST.EmployeeID = @TargetEmployeeID

How would I do this using HQL?

A: 

This is actually very simple in HQL. Try this:

SELECT Case c INNER JOIN FETCH c.Employee WHERE c.Employee.EmployerIdentifier=:employerId

If I remember right, though, this will bypass lazy loading if that's something you're concerned with.

Brad Heller
This doesn’t achieve what I was looking for. Note in the above sql I have to join twice to the employee table. To do it the way you suggest I would need to have the EmployeeIdentifier but I don't have that initially. I could make a round trip to the DB to get it but I was trying to avoid that.
Kevin