Jackson serialize problem in @ManyToMany relationship

Deadly 提交于 2020-12-19 04:20:06

问题


I have the following situation:

//--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();

next class

@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<>();

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!


回答1:


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

and

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "idgruppo")
class Gruppi {
...
}


来源:https://stackoverflow.com/questions/61392551/jackson-serialize-problem-in-manytomany-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!