gpt4 book ai didi

json - Jackson 在@ManyToMany 关系中序列化问题

转载 作者:行者123 更新时间:2023-12-04 10:09:42 27 4
gpt4 key购买 nike

我有以下情况:

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

当我运行应用程序时,一切正常,我得到
enter image description here
当我序列化我的对象 User 时,jackson 序列化除 users_group 之外的所有内容,那是因为我使用的是 @JsonBackReference。但是如果不使用@JsonBackReference 会出现循环问题。我怎样才能获得users_group 序列化呢??我需要它!

最佳答案

对于这两个类,您应该定义一些 ID属性,我们可以用来识别数据库中的对象。我们可以用它来帮助Jackson在运行时识别实例。您可以删除 @JsonBackReference@JsonManagedReference而是使用 com.fasterxml.jackson.annotation.JsonIdentityInfo注解:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property = "iduser")
class User {
...
}


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

关于json - Jackson 在@ManyToMany 关系中序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61392551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com