@jsonbackreference不绑定关系

时间:2016-04-12 07:50:00

标签: java hibernate jackson

我有两个班级:

Person.java:

@Entity
@PrimaryKeyJoinColumn(name="owner_id")
public class Person extends Owner {

    @ManyToOne
    @JoinColumn(name = "car_sharing_id")
    @JsonBackReference
    private CarSharing carSharing;
}

CarSharing.java:

@Entity
public class CarSharing extends MetadataEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne
    @JoinColumn(name = "owner_id", nullable = false)
    @NotNull
    private Person owner;

    @OneToMany(mappedBy = "carSharing", cascade = CascadeType.ALL)
    @Valid
    private Set<Person> members;
}

我正在使用@JsonBackReference来避免无限循环。 CarSharing类工作正常,问题只发生在Person类。

让这个人似乎忽略了carSharing属性。由于在返回服务器时为null,更新会取消对carsharing_id表中person的引用的链接。

停止循环很好,但我还需要carSharing类中的Person

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是Jackson 2.x,则可以使用注释@JsonIdentityInfo

  

是否要使用对象标识信息来确定如何将属性值序列化/从JSON(和其他数据格式)序列化/反序列化将基于@JsonIdentityInfo注释的存在(或缺少)。
见:http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

例如,如果您注释班级CarSharing

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
//...
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class CarSharing {

一个人的JSON结果(我在这个类中添加了一个字段名称)是:

  {
    "carSharing": {
      "@id": 1,
      "id": 12345,
      "owner": {
        "carSharing": 1,
        "name": "owner"
      },
      "members": [
        {
          "carSharing": 1,
          "name": "owner"
        },
        {
          "carSharing": 1,
          "name": "driver2"
        },
        {
          "carSharing": 1,
          "name": "driver"
        }
      ]
    },
    "name": "driver2"
  }

带有id=12345的CarSharing实例:

  {
    "@id": 1,
    "id": 12345,
    "owner": {
      "carSharing": 1,
      "name": "owner"
    },
    "members": [
      {
        "carSharing": 1,
        "name": "owner"
      },
      {
        "carSharing": 1,
        "name": "driver2"
      },
      {
        "carSharing": 1,
        "name": "driver"
      }
    ]
  }

字段@id由杰克逊生成。如果引用的对象未序列化,则该值将设置为引用对象的@id