如何处理多个JsonManagedReference和JsonBackReference?

时间:2015-11-06 23:25:01

标签: java json hibernate jackson

我有以下型号:

model

这是我的代码(我删除了访问器和无用的属性以增加可靠性):

A:

@Entity
@Table(name = "a", schema = "public")
public class A implements Serializable {
    @Id
    private Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.a", cascade = CascadeType.ALL)
    @JsonManagedReference("a")
    private Set<A_B> ABs = new HashSet<>();
}

B:

@Entity
@Table(name = "b", schema = "public")
public class B implements Serializable {
    @Id
    private Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.b", cascade = CascadeType.ALL)
    @JsonManagedReference("b")
    private Set<A_B> ABs = new HashSet<>();
}

A_B:

@Entity
@Table(name = "a_b", schema = "public")
@AssociationOverrides({
        @AssociationOverride(name = "pk.a",
                joinColumns = @JoinColumn(name = "a_id")),
        @AssociationOverride(name = "pk.b",
                joinColumns = @JoinColumn(name = "b_id"))
})
public class A_B implements Serializable {
    @EmbeddedId
    private A_BId pk = new A_BId();

    @OneToOne
    private B b;
}

A_BId:

@Embeddable
public class A_BId implements Serializable {
    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference("a")
    private A a;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference("b")
    private B b;
}

我正在使用com.fasterxml.jackson.datatype:jackson-datatype-hibernate4来解析json中的对象。

  1. 当我解析A时,我希望从B获取A_B而不从A获取A_B
  2. 相反,当我解析B时,我希望AA_B获得B,而不会从A_B获得A_B
  3. 使用我的实际代码,所有null s'元素始终为@JsonManagedReference("b")。当我删除@JsonBackReference("b")fashionable way时,(1)的结果是我需要的结果,但(2)的结果是无限递归

    有人对我的问题有所了解吗?在此先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我无法找到最终答案,但这是最接近的解决方案

https://github.com/FasterXML/jackson-databind/issues/1091

为每个问题类添加此标记

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =“id”) 公共等级A {