Skip to content

An easy and efficient way to Patch and entity with an incoming Map

Here is an easy way to patch an entity.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

// ... other imports and class definition

public class YourEntityService {

    private final ObjectMapper objectMapper;

    public YourEntityService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public YourEntity patchEntity(YourEntity entity, Map<String, Object> updates) {
        try {
            // Use readerForUpdating to create an updater for the existing entity
            YourEntity updatedEntity = objectMapper.readerForUpdating(entity)
                    .readValue(objectMapper.writeValueAsBytes(updates));

            return updatedEntity;
        } catch (Exception e) {
            // Handle exceptions appropriately (e.g., logging, throwing custom exceptions)
            throw new RuntimeException("Error patching entity", e);
        }
    }
}

Comments