我有两节课:

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可用。

任何想法如何解决这个问题?

最佳答案

如果使用的是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是从jackson生成的。如果引用对象未序列化,则将值设置为引用对象的@id

10-04 11:38