这是我的问题:
我想通过hibernate条件做一些类似的查询
select employee.name, employee.surname, department.name, position.name, department_position.end_date
from employee, department_position, department, position
where employee.id = department_position.employee_id
and department_position.department_id = department.id
and department_position.position_id = position.id
and department_position.end_date is null
我将班级Employee
映射到员工表
public class Employee {
private int id;
private String name;
private String surname;
private Date startDate;
private Date endDate;
private Set<DepartmentPosition> positions;
}
和DepartmentPosition
(当然包括所有的设置者和获取者)
public class DepartmentPosition {
private int id;
private Department department;
private Position position;
private Employee employee;
private Date startDate;
private Date endDate;
}
我正在使用此标准
session.createCriteria(Employee.class)
.createAlias("Positions", "pos")
.add(Restrictions.isNull("pos.EndDate"));
我的数据库中只有1名员工符合此查询(并且他在null
endDate
中有1个职位),但在结果列表中重复了3次(看起来因为此员工总共有3个职位)
我该如何解决这个问题?
感谢您的回复
答案 0 :(得分:0)
尝试使用Restrictions.isNull("Employee.Position.EndDate")
之类的限制 - 您未在Restriction
中指明Position
属于Employee
的属性。
答案 1 :(得分:0)
您应该在position对象上创建条件,然后使用projection来获取员工。
Criteria criteria = session.createCriteria(DepartmentPosition.class)
.add(Restrictions.isNull("endDate"));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.distinct(Projections.property("employee")));
criteria.setProjection(projList);
答案 2 :(得分:0)
使用criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);