简体   繁体   中英

Hibernate criteria query multiple criteria

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.

Now, I want to get all assignments relative to the professor, ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM