直接自引用导致周期异常

我有一个班级;如下所示:

public abstract class ElasticSearchValue<T> {

  private Long txId;
  private Long currentTxId;
  private T previous;

  public Long getTxId() {
    return txId;
  }

  public void setTxId(Long txId) {
    this.txId = txId;
  }

  public Long getCurrentTxId() {
    return currentTxId;
  }

  public void setCurrentTxId(Long currentTxId) {
    this.currentTxId = currentTxId;
  }

  public Object getPrevious() {
    return previous;
  }

  public void setPrevious(T previous) {
    this.previous = previous;
  }

}

以及扩展上述类的类

public class DailyActivity extends ElasticSearchValue<DailyActivity> {

  Long agentId;
  Date date;
  Long success;

  public Long getAgentId() {
    return agentId;
  }

  public void setAgentId(Long agentId) {
    this.agentId = agentId;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

  public Long getSuccess() {
    return success;
  }

  public void setSuccess(Long success) {
    this.success = success;
  }

  @Override
  public String toString() {
    return agentId + "_" + date.toString();
  }

}

现在,我有一个类型的对象,当我尝试将其转换为JSON字符串时,我得到以下异常:DailyActivity

Cause: com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference lead to cycle (通过 reference chain: com.pr.analysis.DailyActivity[“previous”])

我已经在谷歌上寻找解决方案,但我得到的解决方案要求将以前的价值放在以前的价值上,这不是我打算做的。有没有人遇到同样的问题?谢谢jsonIgnore

编辑我知道课堂上有一个循环,我在问如何反序列化具有自我引用的课程?


答案 1

在这种情况下,您需要注释与@JsonManagedReference的关系,并按如下方式@JsonBackReference

 @ManyToOne
 @JoinColumn(name = "company_id", referencedColumnName = "id")
 @JsonBackReference
 private Company company 

 @OneToMany(mappedBy="company")
 @JsonManagedReference
 private Set<Employee> employee = new HashSet<Employee>();

这里有一个很好的例子


答案 2

SerializationFeature有一个名为 default is 的属性,但您可以设置为跳过此类异常。FAIL_ON_SELF_REFERENCEStruefalse

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);

如果您使用的是SpringBoot,您只需添加您的spring.jackson.serialization.fail-on-self-references=false application.properties