我可以使用JPA或Hibernate注释显式指定要运行以检索关联对象的查询吗?
具体来说,我有以下实体: 导师, 学生, 以及Tutor和Student之间明确的OneToOne关系,教程:
@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;
}
答案 0 :(得分:3)
您应该可以使用custom loader
在Hibernate中执行此操作@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;
}
命名查询中的位置参数(?
)应在运行时由主键自动替换。我没有尝试使用此代码,因此无法保证它能正常工作,但希望它能为您提供一个以何种方式继续操作的提示。