【问题标题】:JsonMappingException: failed to lazily initialize a collection of roleJsonMappingException:未能延迟初始化角色集合
【发布时间】:2019-08-06 00:57:22
【问题描述】:

假设我的 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,我可以使请求工作,但我想要那些奖励子对象。

【问题讨论】:

    标签: java hibernate spring-boot


    【解决方案1】:

    渴望加载是一种设计模式,其中数据初始化发生在现场

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

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

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

    所以只需使用fetch=FetchType.Eager

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

    【讨论】:

    • 如果我有多个急切加载怎么办?因为在那种情况下我得到 MultipleBagFetchException: cannot 同时获取多个包
    猜你喜欢
    • 1970-01-01
    • 2015-05-03
    • 2017-08-16
    • 1970-01-01
    • 2011-04-27
    • 2013-12-08
    • 2020-05-10
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多