限制不适用于createAlias

时间:2014-04-15 22:53:24

标签: java hibernate hibernate-criteria

这是我的问题:

我想通过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个职位)

我该如何解决这个问题?

感谢您的回复

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);