Reputation: 571
I Have a problem with adding many-to-many relationship in my REST api.
Let' say we have two entities with many-to-many relationship - Employee and Task (employee have Set<Task>
and task have Set<Employee>
).
Some specific task is accessible via this endpoint:
http://localhost:8080/api/tasks/2
Tasks assigned to Employee with id 88 is accessible via:
http://localhost:8080/api/employees/88/tasks
The goal is to POST/PATCH this link to the endpoint.
Could you give me a hint, how this endpoint should look like in controller? I tried something like this, but it's not working.
@PatchMapping("/{employeeId}/tasks")
public Task addTask(@RequestBody Task task, @PathVariable Long taskId) { ... }
Second problem - I would linke to use Postman. Could you tell me which Content-Type should I choose? And how should this link be formatted?
Looking forward for your answers!
Do I have to add another constuctor that takes uri?
Upvotes: 0
Views: 2451
Reputation: 1353
By definition the PATCH method applies a partial update to a given resource, while the PUT method is used to replace a given resource entirely. The keyword here is that both PATCH and PUT are specific to a given resource. The POST method is used to create a new resource.
Therefore, it makes sense that if you want to update just a few fields in your resource and you don't need to update it entirely, to use the PATCH method instead of the PUT method.
The PATCH request body describes how the resource shall be updated, with a series of operations. One format that you can use to describe these operations is the JSON Patch.
Since the PATCH operation is specific to a given resource, and making use of the json-patch library, your controller method should be something like:
@PatchMapping("/{employeeId}/tasks/{taskId}")
public Task updateTask(@RequestBody JsonPatch taskPatch, @PathVariable Long employeeId, @PathVariable Long taskId) { ... }
Note that this a different thing than POST, with a different method (updateTask). For example, if you want to update one field from your task resource (given by taskId), your jsonPatch sent in the request body from your client (can be Postman) would be something like
[{
"op":"replace",
"path":"/field",
"value":"newValue"
}]
There are different operations, such as add, remove, replace, copy and test.
Now in your code you will need to apply this patch to the existing resource. This reference shows how can you do that:
https://www.baeldung.com/spring-rest-json-patch
I hope this helps.
Upvotes: 1