using MySQL, Java, Spring Boot and JPA
I have two objects, user and module.
A user can have many modules and a module can have many users.
A module is structured the following way:
@Entity
@Table(name = "module")
public class Module {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
@JoinTable(name="module_users",
joinColumns = @JoinColumn(name="module_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<User> users = new HashSet<>();
A user is structured the following way:
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
public Long id;
public String name;
private String email;
@JsonIgnore
@ManyToMany(mappedBy = "users")
public Set<Module> modules = new HashSet<>();
Having @JsonIgnore annotation does "work" when calling modules, but I also need to call a user and its modules ideally. Any suggestions to support both of these without crashing from circular referencing?
CodePudding user response:
you can use DTO in this case check here
CodePudding user response:
Use these two annotations @JsonManagedReference and @JsonBackReference
Ref: http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
@Entity
@Table(name = "module")
public class Module {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
@JoinTable(name="module_users",
joinColumns = @JoinColumn(name="module_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
@JsonBackReference
private Set<User> users = new HashSet<>();
A user is structured the following way:
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
public Long id;
public String name;
private String email;
@JsonManagedReference
@ManyToMany(mappedBy = "users")
public Set<Module> modules = new HashSet<>();