0
@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;
 }

当我使用多对多关系时,它会在 json 中无限循环,所以我使用了 @JsonBackReference 和 @JsonManagedReference 但它返回如下

当我搜索 /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"
        }
    ]
},

当搜索 /api/banks 时,它只会返回银行而不是人民

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

]

请帮助解决如何像第一个一样在 /api/banks 中返回人

4

1 回答 1

0

@JsonManagedReference 和 @JsonBackReference 的工作原理

@JsonManagedReference 是引用的前向部分——正常序列化的部分。@JsonBackReference 是引用的后面部分——它将从序列化中省略。

这意味着一侧序列化被省略,另一侧将正常序列化。这就是为什么 Bank inside People 序列化但 People inside Bank 被省略的原因。

如果您希望双方正常序列化,请使用@JsonIdentityInfo

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

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

这里id应该是识别每个实体的主键或唯一键。

于 2020-07-12T08:18:11.173 回答