我正在使用 @JsonIgnore
注释来防止在为响应创建 Json 时出现无限循环,它可以很好地满足我的需要,但我想知道是否有其他选择该属性实际上并没有被忽略,但也防止了无限循环。
例如,我的 entityA 具有以下属性:
int id
String name
EntityB example;
和entityB有
int id
String something
EntityA entityAExample //(this one goes with the JsonIgnore)
所以如果我得到 entityA 中的所有寄存器,响应将如下所示:
[{
"id":"1",
"name": "name",
"entityB": {
"id":"1",
"something": "text"
}
}]
实体 B 看起来像:
[{
"id":"1",
"something": "text"
}]
到目前为止,它对我所需要的效果很好,但我希望实体 B 也可以包含实体 A(如果是多对一关系,则为列表),因此响应如下所示:
[{
"id":"1",
"something": "text",
"entityAExample": {
"id":"1",
"name": "name"
}
}]
因此,无论我查询哪个实体,它都会显示相关记录。
最佳答案
这是处理json时常见的双向关系问题。
我认为用 Jackson 解决这个问题的最简单方法是使用 @JsonIdentityInfo
。你只需要用这样的东西来注释你的类:
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class EntityA{
...
}
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class EntityB{
...
}
这样做的目的是,当之前已经序列化的实体(即父实体 (EntityA))必须在无限递归循环开始时进行第二次序列化时,它将不会像往常一样序列化。
相反,它将使用您在注释中指定的属性进行序列化,即 id
。
简而言之,注释允许您指定对象的替代表示形式,该表示形式仅在实体开始无限循环时使用,从而打破该循环。
按照您的示例将导致:
[{
"id":"1",
"name": "name",
"entityB": {
"id":"2",
"something": "text"
"entityAExample": "1"
}
}]
您也可以只注释 EntityB 而不是两个实体,这将导致:
[{
"id":"1",
"name": "name",
"entityB": {
"id":"2",
"something": "text"
"entityAExample": {
"id": "1",
"name": "name",
"entityBExample": "2"
}
}
}]
关于java - 如何处理与 jackson hibernate 的双向一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34532544/