杰克逊在@ManyToMany关系中序列化问题 [英] Jackson serialize problem in @ManyToMany relationship
问题描述
我有以下情况:
//--class user --
private ....
@OneToMany(targetEntity = UserRoles.class, mappedBy = "iduser", fetch = FetchType.LAZY)
@JsonManagedReference
private List<UserRoles> userRoleList = new ArrayList<>();
@OneToOne(targetEntity = Login.class, cascade = CascadeType.ALL)
@JoinColumn(name = "iduser", referencedColumnName = "iduser")
@JsonManagedReference
private Login login;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "n_gruppi_user", joinColumns = { @JoinColumn(name = "iduser") }, inverseJoinColumns = {
@JoinColumn(name = "idgruppo") })
@JsonManagedReference
List<Gruppi> groups = new ArrayList();
下一堂课
@Entity
@Table(name = "gruppi")
@EntityListeners(AuditingEntityListener.class)
@Data
public class Gruppi implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idgruppo;
private long iduser;
private String tipo;
private String nome_gruppo;
private String pass_gruppo;
private String email_gruppo;
private String descr_gruppo;
private Timestamp data_creazione;
@ManyToMany(mappedBy = "groups")
@JsonBackReference
List<User> users_group = new ArrayList<>();
当我运行应用程序时,一切正常,我得到了 当我序列化对象User时,jackson序列化了users_group以外的所有对象,这是因为我正在使用@JsonBackReference.但是如果不使用@JsonBackReference会出现圆度问题.我也如何获得users_group序列化?我需要它!
when i run application, it's all ok and i get When i serialize my object User, jackson serializes everything except users_group, that's because I'm using @JsonBackReference. But if don't use @JsonBackReference circularity problems arise.How can I get users_group serialization too ?? I need it!
推荐答案
对于这两个类,您都应该定义一些ID
属性,我们可以使用它来标识数据库中的对象.我们可以使用它来帮助Jackson
识别运行时中的实例.您可以删除@JsonBackReference
和@JsonManagedReference
,而使用com.fasterxml.jackson.annotation.JsonIdentityInfo
批注:
For both classes you should have defined some ID
property, we can use to identify objects in data base. We can use it to help Jackson
to identify instances in runtime. You can remove @JsonBackReference
and @JsonManagedReference
and instead use com.fasterxml.jackson.annotation.JsonIdentityInfo
annotation:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property = "iduser")
class User {
...
}
和
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property = "idgruppo")
class Gruppi {
...
}
这篇关于杰克逊在@ManyToMany关系中序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!