spring-data-jpa——如果使用了one-to-many,many-to-one的註解,在Jackson進行json字串化時出現錯誤的解決方案

null^發表於2017-11-24

參考資料:

http://blog.csdn.net/remote_roamer/article/details/51330843

http://blog.csdn.net/xiaodaiye/article/details/51118870

在spring-data-jpa中,使用了one-to-many和many-to-one註解,在進行json字串化時出現錯誤。

經查閱資料找到以下解決方法:

通過在主表的pojo中增加@JsonManagedReference來註解關聯欄位:

@OneToMany(cascade = CascadeType.REFRESH, mappedBy="ruleType",targetEntity = Rule.class)
@JsonManagedReference
private Set rule;

在子表的pojo中增加@JsonBackReference來註解關聯欄位

 @ManyToOne(cascade=CascadeType.REFRESH,fetch = FetchType.EAGER)
 @JsonBackReference
 @JoinColumn(name="TYPE_ID")
 private RuleType ruleType;

然後通過Jackson來生成json

new ObjectMapper().writeValueAsString(obj);

 

相關文章