小编典典

JPA:如何为3个级别定义@NamedEntityGraph?

hibernate

我有3个实体。分支,主题,主题。分支具有主题列表,而主题具有主题列表。而且subjectList和topicList都是惰性的。我想在单个查询中获取所有分支,包括其主题和主题。

1。

@Entity
public 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。

@Entity
public 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。

@Entity
public 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

阅读 1345

收藏
2020-06-20

共1个答案

小编典典

Hibernate不允许您获取多个Bags,因为它最终将获取笛卡尔积。

  1. 您要么创建集合集,要么创建列表,然后面对笛卡尔积性能问题。

  2. 如果您已经具有INNERJOIN关系,则可以简单地从最内层的Child直到根目录进行获取,然后重新组装结构。由于查询如下所示,因此效率更高:

        select t 
    from Topic t
    join t.subject s
    join s.branch b

EntityGraphBuilder,我在我的文章中描述很容易适应你的使用情况。

2020-06-20