2012-12-13 128 views
5

在我当前的项目中,我遇到了一个使用hibernate条件查询获取实体的问题。我有以下实体:休眠条件查询多个条件

  • 教授,其中包含学生
  • 学生,其中包含分配的列表清单。
  • 作业,其中包含它分配给的学生的ID。

现在,我想要得到所有相对于教授的任务,即所有的任务教授分配给他的学生。

此查询显示我想在条件查询中实现的内容。

select * from Assigment p, Student a, Professor c where p.studentid = a.id and a.proffid = c.id and c.id = 2411; 

如何使用hibernate标准API实现此查询?

回答

12

假设你的表像:

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

@Entity 
public class Student{ 
    K profid; 
    List<Assignments> assignments; 
} 

@Entity 
public class Assignments{ 
    K studentid; 
} 

简单的样品通过使用别名:

Criteria criteria = currentSession.createCriteria(Professor.class, "professor"); 
    criteria.createAlias("professor.students", "student"); 
    criteria.createAlias("student.assigments", "assigment"); 
    criteria.add(Restrictions.eqProperty("professor.id", "student.profid")); 
    criteria.add(Restrictions.eqProperty("assigment.studentid", "student.profid")); 
    criteria.add(Restrictions.eq("id", 2411)); 
return criteria.list(); 
+0

非常感谢您的回答! –

+0

如果我想为'professor.id'添加'Restriction.eq'等于1234,即将属性直接与'Long'比较,该怎么办? –

+0

@KevinMeredith Restrictions.eq(“professor.id”,1234L) – anubina