我在尝试以列表对象的形式将数据从rest控制器发送给postman时遇到了这个错误。我知道是什么导致这个问题,但不知道如何解决?rest实体和控制器的代码如下:
@Entity
@Table(name = "posts")
public class PostEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@OneToMany(mappedBy = "postEntity")
private List<CommentEntity> comments;
// getters and setters below
}
@Entity
@Table(name = "comments")
public class CommentEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE,CascadeType.DETACH, CascadeType.REFRESH})
@JoinColumn(name = "post_id")
private PostEntity postEntity;
// getters and setters
}
public List<PostEntity> getFilteredData() {
List<PostEntity> posts = postService.findAll();
return posts;
}
错误消息:
2021-02-11 20:03:57.417 ERROR 26199 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]
: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)
(through reference chain:
com.akashmjain.BlogApplication.enitity.UserEntity["posts"]->org.hibernate.collection.internal.Pe
rsistentBag[0]->com.akashmjain.BlogApplication.enitity.PostEntity["author"]->com.akashmjain.Blog
Application.enitity.UserEntity["posts"]->org.hibernate.collection.internal.PersistentBag[0]->com
.akashmjain.BlogApplication.enitity.PostEntity["author"]->com.akashmjain.BlogApplication.enitity.UserEntity["posts"]->org.hibernate.collection.internal.PersistentBag[0]->com.akashmjain.BlogApp
lication.enitity.PostEntity["author"]->
com.akashmjain.BlogApplication.enitity.UserEntity["posts"]->org.hibernate.collection.internal.PersistentBag[0]->com.akashmjain.BlogApplication.enitity.Po
stEntity["author"]->com.akashmjain.BlogApplication.enitity.UserEntity["posts"]->org.hibernate.collection.internal.PersistentBag[0]->com.akashmjain.BlogApplication.enitity.PostEntity["author"]-
>com.akashmjain.BlogApplication.enitity.UserEntity["posts"]->org.hibernate.collection.internal.PersistentBag[0]->com.akashmjain.BlogApplication.enitity.PostEntity["author"]-
这里我认为问题是comment和post实体相互调用getter将数据发送到rest控制器。所以我尝试将tostring()改为只包含基元类型和 Package 类。但还是有同样的错误。我是在这上面写的还是我遗漏了什么?
1条答案
按热度按时间yzxexxkh1#
两个实体之间存在单向关系,这使得jackson由于无限递归而无法序列化/反序列化负载。
您可以尝试以下方法来解决问题:
使用注解对注解列表进行注解
@JsonBackReference
然后在CommentEntity
但这次使用以下注解:你可以在这里查看更多https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion