Search code examples
hibernaterestjpaspring-bootmany-to-many

SpringBoot JPA Many-to-Many relationship - Rest Webservice unable to return child objects


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


Solution

  • By default many-to-many relation fetch with strategy lazy, means until you don't call the method to retrieve the many to many relationship objects from your main Object, hibernate will not load them from the database.

    Please set the fetch strategy EAGER so hibernate will load many2many relationship during the loading of your main object

    fetch=FetchType.EAGER
    

    example code:

    @ManyToMany(mappedBy = "userGroups", fetch = FetchType.EAGER)
    private Set<User> users = new HashSet<User>();