JPA:如何为3个级别定义@NamedEntityGraph?
我有3个实体。分支,主题,主题。分支具有主题列表,而主题具有主题列表。而且subjectList和topicList都是惰性的。我想在单个查询中获取所有分支,包括其主题和主题。
1。
@Entitypublic class Branch implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@OneToMany(mappedBy = "branch")
private List<Subject> subjectList;
//Getters and Setters
}
2。
@Entitypublic class Subject implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@ManyToOne()
private Branch branch;
@OneToMany(mappedBy = "subject")
private List<Topic> topicList;
//Getters and Setters
}
3。
@Entitypublic class Topic implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@ManyToOne()
private Subject subject;
//Getters and Setters
}
我尝试了下面的方法,但是没有用。
@NamedEntityGraph(name="branch_subject", attributeNodes = {
@NamedAttributeNode(value="name"),
@NamedAttributeNode(value="subjectList", subgraph = "subjectListGraph")
},
subgraphs = {
@NamedSubgraph(name="subjectListGraph",
attributeNodes = {
@NamedAttributeNode(value="name"),
@NamedAttributeNode(value = "topicList", subgraph = "topicListGraph")
}
),
@NamedSubgraph(name="topicListGraph",
attributeNodes = {
@NamedAttributeNode("name")
}
)
}
)
另外下面的代码用于从数据库中获取数据,我使用JPQL如下
EntityGraph branchEntityGraph = entityManager .getEntityGraph("branch_subject");
Branch branch = entityManager
.createQuery("SELECT b from Branch b WHERE b.id=:ID",
Branch.class)
.setHint("javax.persistence.loadgraph", branchEntityGraph)
.setParameter("ID", branch1.getId()).getResultList().get(0);
这给下面的例外
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
回答:
Hibernate不允许您获取多个Bags,因为它最终将获取笛卡尔积。
您要么创建集合集,要么创建列表,然后面对笛卡尔积性能问题。
如果您已经具有INNERJOIN关系,则可以简单地从最内层的Child直到根目录进行获取,然后重新组装结构。由于查询如下所示,因此效率更高:
select t from Topic t
join t.subject s
join s.branch b
EntityGraphBuilder
,我在我的文章中描述很容易适应你的使用情况。
以上是 JPA:如何为3个级别定义@NamedEntityGraph? 的全部内容, 来源链接: utcz.com/qa/432783.html