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.