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();
}
我在用玩具取猫时使用相同的想法,因为玩具实体没有其他关系,并且它们被加载没有问题