json infinite recursion in many to many relationship

278 views Asked by At
@Entity
@Table(name = "people")
public class People {
@ManyToMany(fetch = FetchType.LAZY,
               cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, 
                           CascadeType.REFRESH})
@JoinTable(name = "bank_people",
                     joinColumns = @JoinColumn(name = "people_id"),
                     inverseJoinColumns = @JoinColumn(name = "bank_id"))
private List<Bank> banks;

}
     
 @Entity
 @Table(name = "bank")
 public class Bank {
 @ManyToMany(fetch = FetchType.LAZY,
                            cascade = {CascadeType.DETACH, CascadeType.MERGE, 
                                  CascadeType.PERSIST, CascadeType.REFRESH})
 @JoinTable(name = "bank_people",
                        joinColumns = @JoinColumn(name = "bank_id"),
                        inverseJoinColumns = @JoinColumn(name = "people_id"))
 private List<People> peoples;
 }

When I am using Many To Many relationship it goes infinite looping in json so I used @JsonBackReference and @JsonManagedReference but it returning like below

when I searched for /api/peoples

[
{
    "id": 1,
    "name": "John",
    "accountNumber": "123456",
    "accountType": "SA",
    "banks": [
        {
            "id": 1,
            "bankName": "Indian Bank",
            "branch": "Attur",
            "branchCode": "IDIBATR01"
        },
        {
            "id": 2,
            "bankName": "State Bank of India",
            "branch": "Salem",
            "branchCode": "SBIASLM01"
        }
    ]
},

when searched for /api/banks it will return only banks not peoples

[
{
    "id": 1,
    "bankName": "Indian Bank",
    "branch": "Attur",
    "branchCode": "IDIBATR01"
},
{
    "id": 2,
    "bankName": "State Bank of India",
    "branch": "Salem",
    "branchCode": "SBIASLM01"
}

]

please help to reslove how to return people also in /api/banks like the first one

1

There are 1 answers

0
Eklavya On

That how @JsonManagedReference and @JsonBackReference works

@JsonManagedReference is the forward part of reference – the one that gets serialized normally. @JsonBackReference is the back part of reference – it will be omitted from serialization.

That means one side serialization omitted and other side will be serialized normally. That's why Bank inside People serialized but People inside Bank is omitted.

If you want both sides serialized normally then use @JsonIdentityInfo

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class People { ... }

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Bank { ... }

Here id should be the primary key or unique key to identify per entity.