如何在 hibernate 中与 Jackson 处理双向一对一关系

2024-01-03

我在用着@JsonIgnore在为响应创建 Json 时防止无限循环的注释,它可以很好地满足我的需要,但我想知道是否有一些替代方案,该属性实际上不会被忽略,但也可以防止无限循环。

例如,我有entityA具有以下属性:

int id
String name
EntityB example;

and entityB has

int id
String something
EntityA entityAExample //(this one goes with the JsonIgnore)

因此,如果我获取实体A中的所有寄存器,响应将如下所示:

[{
    "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 时常见的双向关系问题。

我认为用杰克逊解决这个问题最简单的方法是使用@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"                                         
                                   }
               }
}]

您也可以使用其他属性,尽管“id”通常工作正常。Here's http://fasterxml.github.io/jackson-annotations/javadoc/2.0.2/com/fasterxml/jackson/annotation/JsonIdentityInfo.html官方文档和wiki http://wiki.fasterxml.com/JacksonFeatureObjectIdentity.

Here's http://www.insaneprogramming.be/blog/2013/07/13/circular-dependencies-with-jackson/一篇文章更详细地解释了这一点another http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion一个展示了解决该问题的其他方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 hibernate 中与 Jackson 处理双向一对一关系 的相关文章

随机推荐