How to copy only updatable values while updating resources through Spring Boot REST API?

Let’s say you are creating an application to manage your daily tasks.

You decide to write REST APIs in Spring Boot.

Following REST API conventions ,

You create an API named /tasks to create a new task using Http POST method.

You store the task in database.

You create an API with the same name /tasks and using different Http method (PATCH) to update specific fields of the tasks.

And you update the task in database.

But how do you make sure only those values you want to update are updated in the database?

Will you create different API s to update different field values ?

That’s a poor design.

Instead you can pass null values for the fields you don’t want to update.

Advertisements

But wait?

Will this work?

Will java update only the non null values while saving the task to database?

It won’t.

If you are mapping the above request to an entity class in Spring Boot , even the null values will be copied and the original value will be overwritten with null (in the above case the value of “priority” will be overwritten to null)

How to solve this?

Fortunately Spring provides a utility method which copies only the non null values from a source object to target object:

BeanUtils.copyProperties(source,target);

So to update only the non null values you can follow the below algorithm:

  1. Fetch the entity from database using the unique identifier.
  2. Copy the values sent by client to the entity class using BeanUtils.copyProperties() method
  3. Save the entity value to the database.

Here is a sample code:

	@PatchMapping("/tasks/{id}")
	public Task updateTask(@RequestBody UpdateTask request,@PathVariable String id) {

       //fetch from backend
        Task task = service.getTask(id);

       //copy only non null values
		BeanUtils.copyProperties(request, task);

       //save back to backend
		service.updateTask(task);

		return task;
	}

In the above code,

“UpdateTask” request class has the same fields as the entity class “Task”

The entity to be updated is first fetched from backend database using the unique identifier.

And then the non null values are copied from “UpdateTask” model object to “Task” entity object.

And finally the entity is saved back to the database .

Except the non null values , the other values remain intact.

This way you can update any field(s) of a resource using a single REST API.

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s