Reputation: 989
i have a relationship from user and role where role have "one to many" relation and user have "many to one" relation with column "role_id"
when i use relationship on spring boot i got infinite loop data when i use @OneToMany and @ManyToOne so i search and i get @JsonManagedReference and @JsonBackRefence. that solved my problem for inifinite loop.
but when i use @JsonManagedReference(for role) and @JsonBackRefence(for user), for role model that work with what i want. like this screenshot :
but in user model, there are no role data, like this screenshot
what i want is when i get the role data same as what i want (1 screenshot) and when i get data from user, i want the data like this screenshot :
this is my role model :
public class Role {
/*
another data
*/
@JsonManagedReference(value = "user-role")
@OneToMany(
cascade = CascadeType.ALL,
mappedBy = "role"
)
private List<User> users = new ArrayList<>();
}
and my user model :
public class User {
/*
another data
*/
@JsonBackReference(value = "user-role")
@ManyToOne
@JoinColumn(name="role_id")
@OnDelete(action = OnDeleteAction.CASCADE)
private Role role;
}
i have searched many time in stackoverflow and other website but i didn't find any solution, can you help me to solve my problem, thanks a lot.
Upvotes: 6
Views: 2822
Reputation: 7624
You need to add annotation other way around
@JsonManagedReference(for User) and @JsonBackRefence(for Role)
in short, @JsonBackRefence
will ignore were ever added.
You can refer this for more detail
Or see a Demo here with the different use cases.
Upvotes: 2
Reputation: 909
It looks like you are not providing the value of the @JsonManagedReference
Try doing this:
@JsonManagedReference(value = "user-role")
and
@JsonBackReference(value = "user-role")
To exactly specify which reference should be managed.
Upvotes: 1