skip to Main Content

I have this service method for my edit API that maps my pojo class to an entity class for update operation. The CustomerDetail is my Dto class.

public CustomerRegistration editCustomerDetails
(Long id, CustomerDetail customerDetail) throws JsonMappingException 

{

        CustomerRegistration customer = customerRegistrationRepository.findByRegistrationId(id);
        if (customer == null)
            return null;

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.updateValue(customer, customerDetail);
        customer.setModifiedTs(Timestamp.valueOf(LocalDateTime.now()));
        customerRegistrationRepository.save(customer);
        return customer;

    }

Let’s say I want to update the customer details of customerID 1, my request body consists of these fields:

{
"firstName":"Leon",
"middleName":"",
"lastName":"Kennedy",
"addr1":"cross",
"addr2":"new"
}

My customer table already has a middle name for customerID 1. I want to ignore the update operation for middleName field in the table as the request body has an empty string. In my case it is being set to null/empty in the table. How can I avoid this?

My pojo class has already been annotated with @JsonInclude(Include.NON_NULL)

2

Answers


  1. Try changing annotation value from

    @JsonInclude(Include.NON_NULL) // ignores null values
    

    To :

    @JsonInclude(Include.NON_EMPTY) // ignores empty values (empty string, null, etc)
    
    Login or Signup to reply.
  2. It seems to me that you try to achieve very specific logic by means of general purpose method.

    objectMapper.updateValue executes very simple logic: converting source object to the type of target object and then merging result into target object.

    In your case you want to apply specific logic (skip updating a field of target object in case it’s empty in the source object). This logic is not assumed by this method. There’s even no parameter in this method that could switch on/off this logic.

    You may use objectMapper.readValue to parse input string into target object, but then apply the merge logic you want manually.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search