【问题标题】:Restrictions don't work for createAlias限制不适用于 createAlias
【发布时间】:2014-04-15 22:53:24
【问题描述】:

这是我的问题:

我想通过休眠条件执行类似此查询的操作

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(当然还有所有的setter和getter)

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 名员工与此查询匹配(他有 1 个职位,nullendDate),但在结果列表中重复了 3 次(看起来因为该员工总共有 3 个职位)

我该如何解决这个问题?

感谢您的回复

【问题讨论】:

    标签: java hibernate hibernate-criteria


    【解决方案1】:

    使用条件.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    【讨论】:

      【解决方案2】:

      尝试使用 Restrictions.isNull("Employee.Position.EndDate") 之类的限制 - 您没有在 Restriction 中指定 PositionEmployee 的属性。

      【讨论】:

      • 无需指定。 createALias 方法适用于根对象。
      【解决方案3】:

      您应该在职位对象上创建标准,然后使用投影来获取员工。

      Criteria criteria = session.createCriteria(DepartmentPosition.class)
          .add(Restrictions.isNull("endDate"));
      
      ProjectionList projList = Projections.projectionList();
      projList.add(Projections.distinct(Projections.property("employee")));
      criteria.setProjection(projList);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-25
        • 2016-12-30
        • 2014-07-20
        • 1970-01-01
        相关资源
        最近更新 更多