我可以使用JPA或Hibernate注释显式指定要运行的查询以检索关联对象吗?
具体来说,我有以下实体: Tutor(导师), Student(学生), 以及Tutor和Student之间的显式OneToOne关系,Tutorial(教程):
@Entity
public class Student {
@OneToMany Collection<Tutorial> tutorials;
}
@Entity
public class Tutor {
@OneToMany Collection<Tutorial> tutorials;
}
@Entity
public class Tutorial {
@OneToOne Tutor tutor;
@OneToOne Student student;
// other data
}
在教程中,导师可以给学生分配作业(但不能是被未分配到的导师),因此:
@Entity
public class Homework {
@ManyToOne Tutorial tutorial;
// other data
}
现在我想检索学生的所有作业:
@Entity
public class Student {
@OneToMany Collection<Tutorial> tutorials;
@OneToMany Collection<Homework> homework;
}
但是一份作业没有学生,它有一个教程。这在SQL中很容易表达:
select a.*
from Homework a
join Tutorial b on (a.tutorial_id = b.id)
where b.student_id = ?student.id?
我能否使用JPA或Hibernate或Spring注解直接在学生类中表达这个问题,以便在调用Student.getHomework()时使用?
换句话说,我想要的是:
@Entity
public class Student {
@OneToMany Collection<Tutorial> tutorials;
@ExplicitQuery("select Homework where Homework.student = this or something")
@OneToMany Collection<Homework> homework;
}