Reputation: 29
I need to get different parameters in response for 2 different APIs getAll
and getbyID
.
Now I get the same result -second json
for both APIs.
I want to get 1st json in reponse of api getALL
without the one-to-many relation and
I want to get 2nd json in reponse of api getbyid
with one-to-many relation
First JSON Response:
{
"id":2,
"itemName":"book",
}
Second JSON Response:
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John"
}
}
User Class
public class User {
public int id;
public String name;
@JsonBackReference
public List<Item> userItems;
}
Item class
public class Item {
public int id;
public String itemName;
@JsonManagedReference
public User owner;
}
can anyone help in this?
Upvotes: 0
Views: 50
Reputation: 121
My suggestion is to make item class just for data transfer like:
public class ItemDTO {
public int id;
public String itemName;
}
Then in your controller you can do something like that:
@GetMapping('/get-all')
public ResponseEntity<ItemDTO> getAll() {
//get Item object
Item item = //e.g database call
ItemDTO itemDTO = new ItemDTO(item.id, item.name);
return ResponseEntity.ok(itemDTO);
}
@GetMapping('/get-by-id/{id}')
public ResponseEntity<Item> getAll(@PathVariable Integer id) {
Item item = //e.g get item by id
return ResponseEntity.ok(item);
}
Upvotes: 1