By Alex Roig


2019-01-11 11:14:07 8 Comments

I'm wondering what's the best practice when using a PUT method to update a specific property of an entity stored in DB.

Let's see for example the following json that is received on the Rest Controller:

{"id":1, "surname":"Doe"}

The entity that we have stored looks something like this:

public class Employee {
    Long id;
    String name;
    String surname;
    Date createdAt;
    Date updatedAt;
}

I omitted the annotations for simplicity purposes.

What I'd like to achieve is that on the RestController I receive something like this:

@PutRequest
public Employee updateEmployee(@RequestBody Employee employee) {
    repo.saveAndFlush(employee);
}

So, if I do it, then the existing fields for the name and timestamps will be set to null because the provided entity doesn't contain such fields.

I'm wondering if there's a way to run the following actions:

  • Load the entity with the ID provided on DB
  • Update the fields provided in the Json/Request Body.
  • Persist the updated entity -> This can be done the same way I've showed in the code.

I'm aware that it exists the @JsonIdentity and @JsonIdentifyreference(alwaysAsId=true) which I use in conjunction with resolvers to fetch the data from DB for fetching a nested entity where only the ID is provided rather the entity itself.

1 comments

@Shadov 2019-01-11 11:18:52

PATCH method is designed for that functionality.

PUT should be used when you are replacing the whole resource - that means setting null on fields that you didn't provide in request.

PATCH is used for updating a resource, you can update a single field, or all the fields, your choice.

Be aware that the actual database update may not automagically work, just because you changed the HTTP method. For Hibernate there is a @DynamicUpdate that provides the same functionality. Without @DynamicUpdate the fields set to null will be updated, but with @DynamicUpdateonly the fields that were modified will be updated.

@Roman Vottner 2019-01-11 11:38:34

To be more precise, patch is a set of instructions a server should apply on certain resources to transform the state of the resource to a desired one. As also mentioned by William Durand using JSON Merge Patch format is probably the closes thing to what plenty of people consider a partial update done either via PUT or PATCH.

Related Questions

Sponsored Content

3 Answered Questions

9 Answered Questions

[SOLVED] How to add custom method to Spring Data JPA

4 Answered Questions

[SOLVED] Create the perfect JPA entity

0 Answered Questions

0 Answered Questions

Spring boot validate multiple object from map

18 Answered Questions

[SOLVED] Infinite Recursion with Jackson JSON and Hibernate JPA issue

3 Answered Questions

2 Answered Questions

1 Answered Questions

[SOLVED] Spring Data JPA and PUT requests to create

Sponsored Content