Jackson 在@ManyToMany 关系中序列化问题 [英] Jackson serialize problem in @ManyToMany relationship

查看:18
本文介绍了Jackson 在@ManyToMany 关系中序列化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

//--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 {
...
}

这篇关于Jackson 在@ManyToMany 关系中序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆