gpt4 book ai didi

java - JsonMappingException : failed to lazily initialize a collection of role

转载 作者:行者123 更新时间:2023-11-30 05:43:52 31 4
gpt4 key购买 nike

假设我的 Java、Spring Boot、Hibernate 应用程序中有这个类:

@Entity
@Table(name="person")
@Getter @Setter @NoArgsConstructor
public class Person{

@Id
@Column(name="ID", nullable=false)
private int Id;

@Column(name="PERSON_ID")
private String personId;

@Column(name="FIRST_NME")
private String firstName;

@Column(name="LAST_NME")
private String lastName;

@OneToMany(fetch=FetchType.LAZY, mappedBy = "person", cascade = {CascadeType.ALL})
private List<Award> awards;
}

假设这是奖项类别:

@Entity
@Table(name="award")
@Getter @Setter @NoArgsConstructor
public class Award{

@Id
@Column(name="COMPOSITE_ID", nullable=false)
private int Id;

@Column(name="AWARD_CODE")
private String awardCode;

@Column(name="AWARD_NAME")
private String awardName;

@ManyToOne
@JoinColumn(name="PERSON_ID")
private Personn person;
}

当我从我的 jpa 存储库中进行简单的查找时,如下所示:

List<Person> findAll();

我收到此错误:

failed to lazily initialize a collection of role: com.my.proj.datastores.legacy.model.Person.awards, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.my.proj.datastores.legacy.model.Person.awards, could not initialize proxy - no Session (through reference chain: com.my.proj.datastores.ngl.model.Person["awards"])]

不太清楚为什么......如果我执行@JsonIgnore,我可以使请求工作,但我想要那些奖励子对象。

最佳答案

预加载是一种当场进行数据初始化的设计模式

延迟加载是一种设计模式,用于尽可能推迟对象的初始化

当启用延迟加载时,如果我们拉起一个 Person,奖励数据将不会被初始化并加载到内存中,直到对其进行显式调用。

在急切加载策略中,如果我们加载 Person,它也会加载与其关联的所有 Award 并将其存储在内存中。

所以只需使用fetch=FetchType.Eager

@OneToMany(fetch=FetchType.Eager, mappedBy = "person", cascade = {CascadeType.ALL})
private List<Award> awards;

关于java - JsonMappingException : failed to lazily initialize a collection of role,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174242/

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