使用 jackson 将双向 JPA 实体序列化为 JSON

2022-09-02 19:40:34

我正在使用Jackson将我的JPA模型序列化为JSON。

我有以下类:

import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.Set;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class)
@Entity
public class Parent {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  @JsonManagedReference
  @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  private Set<Child> children;

  //Getters and setters
}

import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class Child {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  @JsonBackReference
  @ManyToOne
  @JoinColumn(name = "parentId")
  private Parent parent;

  //Getters and setters
}

我正在使用POJO映射从模型序列化到JSON。当我序列化父对象时,我得到以下 JSON:

{
  "id": 1,
  "name": "John Doe",
  "children": [
    {
      "id": 1,
      "name": "child1"
    },{
      "id": 2,
      "name": "child2"
    }
  ]
}

但是当我序列化一个孩子时,我得到以下JSON:

{
  "id": 1,
  "name": "child1"
}

缺少对父项的引用。有没有办法解决这个问题?


答案 1

我认为你必须在和/ 之间做出选择。@JsonIdentityInfo@JsonBackReference@JsonManagedReference

我会去:在您的实体上,删除/对。@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id")@JsonBackReference@JsonManagedReference

并添加要排除的字段。@JsonIgnore


答案 2

您可以使用JsonManagedReference / JsonBackReference,同时使用JsonIdentityInfo来补充双向关系。

有问题的类:

// bi-directional one-to-many association to Answer (Question is owner)
@JsonManagedReference
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@QuestionAnswers")
private Set<Answer> answers = new HashSet<>();

在回答类: // 双向多对一关联到问题

@JsonBackReference
@ManyToOne
@JoinColumn(name = "questionId", referencedColumnName="id", foreignKey = @ForeignKey(name = "fk_answer_question"))
private Question question;

如果您需要子对象中的父引用,请删除托管/后退引用,这对我来说很好。