Tora Tora Tora
Tora Tora Tora

Reputation: 993

SpringBoot JPA Many-to-Many relationship - Rest Webservice unable to get all child attributes in Get All

I have a simple many to many relationship : Owner <-> Book <-> Publisher

I notice an odd behavior: When I get the specific Book, the Publisher and Owner (child entities) information is fetched along with all attributes. However, in Get All Books, the child’s attributes are missing.

When I do a GET to a specific Book, I get all attributes of both Book and its child:

cURL -XGET http://localhost:8080/books/isbn/978-0743246264

{
   "id":4,
   "name":"Book 4",
   "isbn":"978-0743246264",
   "publishers":[
      {
         "id":1,
         "name":"Publisher 1",
         "description":"Description - 1"
      }
   ],
   "owners":[
      {
         "id":3,
         "name":"Owner 3"
      }
   ]
}

However, when I run GET for all books, the child attributes are missing for some elements:

cURL -XGET http://localhost:8080/books

[
   {
      "id":1,
      "name":"Book 1",
      "isbn":"978-0743246261",
      "publishers":[
         {
            "id":1,
            "name":"Publisher 1",
            "description":"Description - 1"
         },
         {
            "id":2,
            "name":"Publisher 2",
            "description":"Description - 2"
         }
      ],
      "owners":[
         {
            "id":1,
            "name":"Owner 1"
         }
      ]
   },
   {
      "id":2,
      "name":"Book 2",
      "isbn":"978-0743246262",
      "publishers":[
         {
            "id":4,
            "name":"Publisher 4",
            "description":"Description - 4"
         },
         1,
         {
            "id":3,
            "name":"Publisher 3",
            "description":"Description - 3"
         }
      ],
      "owners":[
         {
            "id":2,
            "name":"Owner 2"
         },
         {
            "id":3,
            "name":"Owner 3"
         },
         1
      ]
   },
   {
      "id":3,
      "name":"Book 3",
      "isbn":"978-0743246263",
      "publishers":[
         4,
         2
      ],
      "owners":[
         2
      ]
   },
   {
      "id":4,
      "name":"Book 4",
      "isbn":"978-0743246264",
      "publishers":[
         1
      ],
      "owners":[
         3
      ]
   }
]

I’ve setup the project on GitHub and it is ready to run and test right away: https://github.com/tekpartner/learn-spring-boot-many-2-many

Upvotes: 0

Views: 60

Answers (1)

O.Badr
O.Badr

Reputation: 3141

Remove @JsonIdentityInfo annotation from both Publisher and Owner class, so Jackson will serialize a full version of the class instead of using their id as a reference.

Upvotes: 1

Related Questions