java Hibernate 条件查询多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13858876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:13:00  来源:igfitidea点击:

Hibernate criteria query multiple criteria

javahibernatehibernate-criteria

提问by ilya.stmn

In my current project I've faced a problem of getting entities with hibernate criteria query. I have the following entities:

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

  • Professor, which contains a list of students
  • Student, which contains a list of assignments.
  • Assignment, which contains id of student to which it is assigned to.
  • 教授,其中包含学生列表
  • 学生,其中包含作业列表。
  • 作业,其中包含分配给它的学生的 ID。

Now, I want to get all assignments relative to the professor, i.e. all assignments Professor assigned to his students.

现在,我想获得与教授相关的所有作业,即教授分配给他的学生的所有作业。

This query shows what I want to implement in criteria query.

此查询显示了我想在标准查询中实现的内容。

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

How can I implement this query using hibernate criteria API?

如何使用休眠条件 API 实现此查询?

回答by Teifi

suppose your tables like that:

假设你的表是这样的:

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

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

@Entity
public class Assignments{
    K studentid;
}

simple sample by using alias:

使用别名的简单示例:

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