我正在开发基于JPA的项目,我有两个实体,比如学生和学校。每个学生都有一所学校。
学生学校属性获取类型是懒惰的,但我需要能够急切地获取学校名称属性。
有没有办法做到这一点?
感谢重新编码
答案 0 :(得分:2)
如果您使用的是JPA 2.1,则可以尝试Entity Graph,指明要加载的属性:
@Entity
@NamedQueries({
@NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s")
})
@NamedEntityGraphs({
@NamedEntityGraph(
name = "studentGraph",
attributeNodes = {
@NamedAttributeNode(value = "id"),
@NamedAttributeNode(value = "name"),
@NamedAttributeNode(value = "school", subgraph = "schoolGraph")
},
subgraphs = {
@NamedSubgraph(
name = "schoolGraph",
attributeNodes = {
@NamedAttributeNode("name")
}
)
}
)
})
public class Student {
@Id
private Long id;
private String name;
@ManyToOne
private School school;
}
使用如下:
List<Student> students = entityManager.createNamedQuery("Student.findAll")
.setHint("javax.persistence.fetchgraph", entityManager.getEntityGraph("studentGraph"))
.getResultList();
实体图也可以动态创建。