I have the following problem:
I have two Entities in hibernate, a Post and a Category.
Every post has a Category and a Category can have multiple posts, thus the mapping is bidirectional and one-to-many/many-to-one type of relationship.
When i want to display a category, I want to display the list of posts with it, and when i display a post I want to display the category with it. Here comes the infinite recursion problem which is solved with two annotations: @JsonBackReference and @JsonManagedReference
When the relationship is defined by the following annotations:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CategoryID")
@JsonManagedReference
private Category category;
@OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
@JsonBackReference
private List<Post> posts;
I get the following JSON:
For category:
{
"id": 1,
"name": "Animals"
}
For post:
{
"id": 1,
"title": "title1",
"description": "description",
"category": {
"id": 2,
"name": "Buisness"
}
}
When the relationship is defined by the following annotations:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CategoryID")
@JsonBackReference
private Category category;
@OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
**@JsonManagedReference**
private List<Post> posts;
I get the following JSON:
For category:
{
"id":2,
"name":"Buisness",
"posts":[
{
"id":1,
"title":"title1",
"description":"description"
}
]
}
For post:
{
"id": 1,
"title": "title1",
"description": "description"
}
I want to display the post like the first example, and the category like the second example, any ideas on how to fix this?