@Override @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) public void updateStore(Integer userId, StoreParam storeParam) throws Exception{ Store store=storeRepo.findTopByStoreId(storeParam.getStoreId()); if(store==null){ //参数错误 throw new Exception("admin-001"); } //将参数中非空的值赋给实体中,并将实体重新存储 JpaUtil.copyNotNullProperties(storeParam, store); storeRepo.save(store); }
封装类
public class JpaUtil { public static void copyNotNullProperties(Object src,Object target){ BeanUtils.copyProperties(src,target,getNullPropertyNames(src)); } 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); } }