1

Message Could not write JSON: failed to lazily initialize a collection of role: core.domain.Cat.catFoods, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: core.domain.Cat.catFoods, could not initialize proxy - no Session (through reference chain: web.dto.ToysDTO["toys"]->java.util.HashSet[0]->web.dto.ToyDTO["cat"]->core.domain.Cat["catFoods"])

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

我有以下实体:Toy、Cat、CatFood 和 Food。基本上,猫与玩具的关系是 1:1,而猫和食物是使用 CatFood 的 m:n 关系。

@NamedEntityGraphs({
        @NamedEntityGraph(name = "toyWithCat",
                attributeNodes = @NamedAttributeNode(value = "cat"))
})
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode(callSuper = true)
@Entity
public class Toy extends BaseEntity<Long> {
    String name;
    int size;

    public Toy(Long id, String name, int size) {
        this.setId(id);
        this.name = name;
        this.size = size;
    }

    @JsonBackReference(value = "cat-reference")
    @OneToOne(mappedBy = "favoriteToy")
    private Cat cat;

}
@NamedEntityGraphs({
        @NamedEntityGraph(name = "catWithToy",
                attributeNodes = @NamedAttributeNode(value = "favoriteToy")),
        @NamedEntityGraph(name = "catWithCatFoodAndFood",
                attributeNodes = @NamedAttributeNode(value = "catFoods",
                        subgraph = "catFoodWithFood"),
                subgraphs = @NamedSubgraph(name = "catFoodWithFood",
                        attributeNodes = @NamedAttributeNode(value = "food")))
})
@Entity
public class Cat extends BaseEntity<Long> {
    String name, breed;
    Integer catYears;
    @JsonManagedReference(value = "cat-reference")
    @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true)
    @JoinColumn(name = "toy_id", referencedColumnName = "id")
    private Toy favoriteToy;

    @JsonManagedReference(value = "cat-reference")
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "cat", cascade = {CascadeType.REMOVE}, orphanRemoval = true)
    Set<CatFood> catFoods;

我正在尝试调用此函数

public interface ToyRepository extends Repository<Toy, Long> {
    @Query("select distinct t from Toy t")
    @EntityGraph(value = "toyWithCat", type = EntityGraph.EntityGraphType.LOAD)
    List<Toy> getToysWithCat();
}

我在用玩具取猫时使用相同的想法,因为玩具实体没有其他关系,并且它们被加载没有问题

4

1 回答 1

0

在您Toy使用的类中,@EqualsAndHashCode这将在hashCode()基于该类的所有属性计算 hashCode 的实现中得到解决。

这意味着你的Toy类中的 hashCode 方法调用了hasCodeon 方法Cat。在 cat 中有一个SetwhichCatFoods被映射,Cat这意味着涉及计算hashCode属性的catFoodsCat为了计算 Cat 的 hashCode 它再次开始hashCode计算SetCatFoods

(听起来令人困惑,但目前我无法更好地描述它)

由于没有活动会话,因此无法获取计算 hashCod 所需的惰性集合。这就是为什么你得到这个例外。

要点:从计算中明确排除LAZY获取的属性。@EqualsAndHashCode您可以使用注释这些属性@EqualsAndHashCode.Exclude以将它们从 hashCode 计算中排除。

要查看 hashCode 计算的实现,您可以使用 IntelliJ 的 DeLombok 功能。

于 2021-05-18T07:52:14.457 回答