Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonManagedReference and @JsonBackReference cannot get relation data from jsonbackreference model

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 :

enter image description here

but in user model, there are no role data, like this screenshot enter image description here

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 : enter image description here

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.

like image 357
Rizal Sidik Avatar asked Oct 27 '22 03:10

Rizal Sidik


1 Answers

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.

like image 78
Rohan Shah Avatar answered Nov 02 '22 22:11

Rohan Shah