有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

名为“defaultReference”的java多个反向引用属性

我在一个课堂上有多个反向参考课。因为我对它们使用了@JsonBackReference,所以我得到了一个错误。我为这些类分配了@JsonIdentityInfo注释,但仍然得到相同的错误

public class X implements Serializable {
  ....
  //bi-directional many-to-one association to Booking
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "xxA", nullable = false)
  @JsonBackReference
  private A a;

  //bi-directional many-to-one association to Client
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "xxB", nullable = false)
  @JsonBackReference
  private B b;
  ...getters setters
}

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class B implements Serializable {
  ........ 
  //bi-directional many-to-one association to BookedClient
  @OneToMany(mappedBy = "b", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JsonManagedReference
  private List < X > xxB;
  ........ getters setters
}


@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class A implements Serializable {
  ........
  //bi-directional many-to-one association to BookedClient
  @OneToMany(mappedBy = "a", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JsonManagedReference
  private List < X > xxA;
  ........ getters setters
}

错误:

com.fasterxml.jackson.databind.JsonMappingException: Multiple back-reference properties with name 'defaultReference'

如何解决此错误?我不能在一个类中使用多个反向引用吗


共 (2) 个答案

  1. # 1 楼答案

    所以这确实花了我一段时间

    您可以使用@JsonIdentityReference(alwaysAsId = true)相应地注释您的引用,然后将其保留在主引用之外

        @JsonIdentityReference(alwaysAsId = true)
        private Set<PackInstructionGroup> groups = new TreeSet<>();
    
  2. # 2 楼答案

    我也面临着这个问题,但最后我解决了

    //This is parent class
    @Entity
    @Table(name = "checklist")
    @JsonIgnoreProperties("inspection")
    public class Checklist implements java.io.Serializable {
    
        @ManyToOne
        @JoinColumn(name = "product_id", referencedColumnName = "id")
        @JsonBackReference
        private Product product;
    
        @OneToMany(mappedBy = "checklists", cascade = CascadeType.ALL)
        @JsonManagedReference
        private Set<Inspection> inspection = new HashSet<Inspection>();
    //Constructor
    //Getter and Setter
    }
    
    //This is child class
    @Entity
    @Table(name = "inspections")
    public class Inspection {
    
        @ManyToOne
        @JoinColumn(name = "chk_id", referencedColumnName = "id")
        private Checklist checklists;
    //Constructor
    //Getter and Setter
    }
    

    通过在父类中提到@JsonIgnoreProperties("inspection")@JsonManagedReference

    解决了在同一父类中使用两个@JSONBackRefrence所引发的问题