gpt4 book ai didi

java - Hibernate:无需多个包即可获取对象集合

转载 作者:行者123 更新时间:2023-12-01 14:59:32 25 4
gpt4 key购买 nike

当我尝试获取我的 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 主题中排除,现在又遇到了另一个异常。我还在 DAO 类中的方法中添加了 criteria.setFetchMode("projects", FetchMode.JOIN);

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

最佳答案

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

首先,确保您确实需要两者。

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

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

关于java - Hibernate:无需多个包即可获取对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com