问题
I have a Dept table and a Emp table.
I need to join these two table in such a way that the where clause looks something like this:
where dept.deptId = emp.DeptId and dept.deptName = emp.empTrainingName
I tried this:
Criteria criteria = session.createCriteria(Dept.class).createAlias("empMap","id");
Using this, the first where condition i.e. dept.deptId = emp.DeptId is performed. But I am not sure how to compare dept.deptName with emp.empTrainingName.
How do I do this using the Criteria API in NHibernate?
回答1:
Criteria criteria = session.createCriteria(Dept.class, "department")
.createAlias("empMap", "employee")
.add(Restrictions.eqProperty("department.deptName",
"employee.empTrainingName"));
You may also use a with clause, which would be necessary in case of a left join:
Criteria criteria =
session.createCriteria(Dept.class, "department")
.createAlias("empMap",
"employee",
Criteria.LEFT_JOIN,
Restrictions.eqProperty("department.deptName",
"employee.empTrainingName"));
Side note: your choices of names are awful. Instead of Dept.deptId, Why not use Department.id? Instead of Emp.empTrainingName, why not choose Employee.trainingName?
来源:https://stackoverflow.com/questions/10967695/joining-on-multiple-fields-in-a-nhibernate-criteria-query