I need help in retrieving data from a Spring Boot application using JPA to handle Many-to-Many relationships. I’m having trouble getting the child entities of a parent entity.
I have a simple many to many relationship established: Owner <-> Book <-> Publisher
When I do a GET on the controller to fetch data about a Book, I only get the Book’s attributes. No information about the associated Owner or Publisher is returned. What am I missing?
Executing cURL -XGET http://localhost:8080/books
only returns the attributes from the book and not the dependent objects:
[
{
"id":1,
"name":"Book 1",
"isbn":"978-0743246261"
},
{
"id":2,
"name":"Book 2",
"isbn":"978-0743246262"
},
{
"id":3,
"name":"Book 3",
"isbn":"978-0743246263"
},
{
"id":4,
"name":"Book 4",
"isbn":"978-0743246264"
}
]
I’ve setup the project in GitHub and it is ready to run and test right away: https://github.com/tekpartner/learn-spring-boot-many-2-many
答案 0 :(得分:2)
默认情况下,使用策略 lazy 进行多对多关系提取,意味着在您不调用方法从主Object检索多对多关系对象之前,hibernate将不会加载它们来自数据库。
请设置获取策略EAGER,以便hibernate在加载主对象时加载many2many关系
fetch=FetchType.EAGER
示例代码:
@ManyToMany(mappedBy = "userGroups", fetch = FetchType.EAGER)
private Set<User> users = new HashSet<User>();
答案 1 :(得分:0)
@ bhushan-uniyal上面提到的解决方案是交换引用JsonManagedReference&amp; JsonBackReference,它的工作原理。推送代码并且工作正常。