2

I wrote an update method which accepts fields that are modified.

 public ResponseEntity<String> updateProduct(@RequestBody final Product product)
 {
  returnValue = productService.updateProduct(product);
 }

Product is a bean class holds 50 property list. From UI if i modify 5 fields it holds those modified fields and other properties as null. How to perform filter here? I want to pass only updated value

 returnValue = productService.updateProduct(product); 
saurav
  • 219
  • 1
  • 13

1 Answers1

4

Its pretty hard to say without seeing any code from the Product class nor the ProductService.updateProduct method. However you may be able to to use the BeanUtilsBean class provided in the Apache Commons library.

public static void nullAwareBeanCopy(Object dest, Object source) throws IllegalAccessException, InvocationTargetException {
    new BeanUtilsBean() {
        @Override
        public void copyProperty(Object dest, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if(value != null) {
                super.copyProperty(dest, name, value);
            }
        }
    }.copyProperties(dest, source);
}

This is one I wrote but since your using spring you may want to use the spring bean utils class located at org.springframework.beans.BeanUtils. Doing a quick search for that code I came across this answer from alfredx which has this code

public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for(java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

// then use Spring BeanUtils to copy and ignore null
public static void myCopyProperties(Object, src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src))
}

You can then use it like:

public void updateProduct(Product updatedProduct) {
    Product existingProduct = /*find existing product*/;
    nullAwareBeanCopy(existingProduct, updatedProduct);
    // or 
    myCopyProperties(updatedProduct, existingProduct);
}

Watchout these 2 different methods source/destination parameters are opposite of eachother.

Community
  • 1
  • 1
ug_
  • 11,267
  • 2
  • 35
  • 52
  • Watch out for updates where the actual new value has to be null ;) if you are never sending "clear" values you can use your approach, else you need a way to track which fields have been set by the request. – Martin Frey May 24 '16 at 10:29