比较Collection的字段 - org.hibernate.QueryException:无法解析属性:

时间:2014-07-21 21:17:00

标签: java hibernate

answer清楚地描述了如何设置Restriction以比较2个属性相等的位置。

在答案中给出了这两个实体:

@Entity
public class Professor{
    K id;
    List<Student> students;
}

@Entity
public class Student{
    K profid;
    String name;
}

我如何撰写以下Restrictionwhere professor.students.name is "Kevin"

我尝试过类似的事情:

Criteria criteria = createCriteria(Professor.class);
criteria.add(Restrictions.eq("students.name", "Kevin")

但是失败了:

org.hibernate.QueryException: could not resolve property: 
     'students.name' of: Professor

1 个答案:

答案 0 :(得分:1)

您需要首先为集合添加别名,例如

Criteria criteria = createCriteria(Professor.class);
criteria.addAlias("students", "s");
criteria.add(Restrictions.eq("s.name", "Kevin")

需要Alias,因为Criteria API不会自动加入