问题
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