我能否使用 JPA 或 Hibernate 注释显式指定要运行的查询以检索关联对象?
具体来说,我有以下实体: 导师, 学生, 以及 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;
}
最佳答案
您应该能够在 Hibernate 中使用 custom loader 执行此操作
@Entity
@NamedNativeQuery(name="customHomeworkLoader", query="select a.* from Homework a join Tutorial b on (a.tutorial_id = b.id) where b.student_id = ?", resultClass = Homework.class)
public class Student {
@OneToMany Collection<Tutorial> tutorials;
@Loader(namedQuery = "customHomeworkLoader")
@OneToMany Collection<Homework> homework;
}
命名查询中的位置参数 (?
) 应该在运行时被主键自动替换。我没有尝试过这段代码,所以不能保证它会工作,但希望它能给你一个提示,告诉你如何继续。
关于hibernate - JPA 或 Hibernate 或 Spring 注释来指定对关系的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26885341/