I am working on a springboot application. I have 2 entity classes, Group and User. I also have @ManyToMany relationship defined in the Group class (Owning entity), and also in the User class, so that I can fetch all the groups a user belongs to. Unfortunately, I can't create a new group or a new user due to the following error;
{
"timestamp": "2022-09-09T20:29:22.606+00:00",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/json;charset=UTF-8' not supported"
}
When I try to fetch all groups a user belongs to by calling user.get().getGroups(); I get a a stack overflow error
Note: Currently I have @JsonManagedReference and @JsonBackReference in Group and User classes respectively. I also tried adding @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") on both classes, but this did not work either. Adding value parameter to @JsonManagedReference and @JsonBackReference as demonstrated below did not work either. What am I doing wrong? What am I missing?
This is my Group entity class
@Table(name = "`group`") // <- group is a reserved keyword in SQL
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JsonView(Views.Public.class)
private String name;
private Integer maximumMembers;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinTable(name = "group_user", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
@JsonView(Views.Public.class)
@JsonManagedReference(value = "group-member")
private Set<User> groupMembers;
}
This is my User entity class
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonView(Views.Public.class)
private Long id;
@JsonView(Views.Public.class)
private String nickname;
@JsonView(Views.Public.class)
private String username; // <- Unique user's phone number
private String password;
@ElementCollection(targetClass = ApplicationUserRole.class)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
@Column(name = "role")
private Set<ApplicationUserRole> roles;
@ManyToMany(mappedBy = "groupMembers", fetch = FetchType.LAZY, targetEntity = Group.class)
@JsonBackReference(value = "user-group")
private Set<Group> groups;
}
Minimal, Reproducible Example https://github.com/Java-Techie-jt/JPA-ManyToMany