json在多对多关系中的无限递归


@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/publics 时

[
{
"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/银行中的人员也像第一个一样返回

@JsonManagedReference和@JsonBackReference如何工作

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

这意味着省略了一侧的序列化,而正常序列化另一侧。这就是为什么银行内部的人连载,但人内部的银行被省略。

如果您希望两边都正常序列化,则使用@JsonIdentityInfo

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

这里,id应该是用于标识每个实体的主键或唯一密钥。

相关内容

  • 没有找到相关文章

最新更新