0

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?

Echoloz
  • 13
  • 4
  • You can use `@JsonIgnoreProperties`, details is [here](https://stackoverflow.com/a/47723808/5380322)... – Cepr0 Aug 05 '18 at 16:39
  • Custom serializers or possibly this https://stackoverflow.com/questions/12141561/serialize-one-class-in-two-different-ways-with-jackson – coladict Aug 06 '18 at 08:39

0 Answers0