英文:
@JsonManagedReference and @JsonBackReference cannot get relation data from jsonbackreference model
问题
我有一个关于用户和角色的关系,其中角色与“一对多”关系,用户与“多对一”关系,列名为“role_id”。
当我在Spring Boot中使用关系时,当我使用@OneToMany和@ManyToOne时,我得到了无限循环的数据,所以我搜索并找到了@JsonManagedReference和@JsonBackReference。这解决了我的无限循环问题。
但是,当我在角色模型上使用@JsonManagedReference(用于角色)和@JsonBackReference(用于用户)时,角色模型可以按照我想要的方式工作。就像这个截图:
但在用户模型中,没有角色数据,就像这个截图:
我想要的是,当我获取角色数据时,与我想要的一样(第一个截图),当我从用户获取数据时,我希望数据像这个截图一样:
这是我的角色模型:
public class Role {
/*
其他数据
*/
@JsonManagedReference(value = "user-role")
@OneToMany(
cascade = CascadeType.ALL,
mappedBy = "role"
)
private List<User> users = new ArrayList<>();
}
这是我的用户模型:
public class User {
/*
其他数据
*/
@JsonBackReference(value = "user-role")
@ManyToOne
@JoinColumn(name="role_id")
@OnDelete(action = OnDeleteAction.CASCADE)
private Role role;
}
我已经在StackOverflow和其他网站上搜索了很多次,但没有找到解决方案,你能帮助我解决我的问题吗?非常感谢。
英文:
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.
答案1
得分: 2
@JsonManagedReference(for User) 和 @JsonBackReference(for Role) 需要添加在另一种方式中,简而言之,@JsonBackReference
会忽略任何地方添加的引用。您可以参考此处了解更多详细信息,或者查看此处的演示,其中包含不同的用例。
英文:
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.
答案2
得分: 1
尝试这样做:
@JsonManagedReference(value = "user-role")
和
@JsonBackReference(value = "user-role")
来精确指定应该被管理的引用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论