0

当我试图获取我的Employee实体列表时,我收到了这个错误:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch 
multiple bags

我的Employee实体类有两个不同对象的列表。我想有问题。

@ManyToMany
@JoinTable(name = "employee_project",
        joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "employee_id")},
        inverseJoinColumns = {@JoinColumn(name = "project_id", referencedColumnName = "project_id")})
protected List<Project> projects;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id")
protected List<EmployeeTheme> themes;

我的实体Project目前没有Employee对象列表。但

public class EmployeeTheme implements Serializable {

    @EmbeddedId
    private EmployeeTheme PK id;

    @ManyToOne
    @JoinColumn(name = "employee_id", nullable = false, insertable = false, updatable = false)
    protected Employee employee;
}

这是我的复合键类:

@Embeddable
public class EmployeeThemePK implements Serializable {

    @Column(name = "employee_id")
    protected Long employeeId;

    @Column(name = "theme")
    protected String theme;
}

如何正确配置这些关系?

编辑

我已将主题和项目的列表切换为设置。我已经从我的 JSON 主题中排除了,现在我遇到了另一个例外。我还在criteria.setFetchMode("projects", FetchMode.JOIN);我的 DAO 类中添加了方法。

failed to lazily initialize a collection of role: com.package.Employee.projects,
no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a 
collection of role: com.package.Employee.projects, no session or session 
was closed


Exception caught during request processing: flexjson.JSONException: Error 
trying to deepSerialize
flexjson.JSONException: Error trying to deepSerialize
4

2 回答 2

1

触发此异常是因为您正在获取员工并急切地获取员工的主题和员工的项目。

首先,确保你真的需要两者。

其次,意识到通过这样做,你正在制作一个笛卡尔积。如果员工有 100 个项目和 100 个主题,则查询将只为该员工返回 10,000 行。也许您应该先获取员工及其项目(100 行),然后重新获取员工及其主题(再次获取 100 行)。

第三,如果笛卡尔积确实是您想要的,那么至少将其中一个集合设为 Set 而不是 List。

于 2012-12-14T13:23:22.463 回答
0

您可以Hibernate.initialize()在 DAO 中使用来获取与您的主要对象相关的特定属性,这样可以避免加载数据,您可能不需要类似的东西:

q = this.entityManager.createQuery('SQL..');
employee= q.getSingleResult();
Hibernate.initialize(employee.themes);
于 2015-10-15T13:48:23.967 回答