zoukankan      html  css  js  c++  java
  • JPA-save()方法会将字段更新为null的解决方法

    Spring data jpa使用save方法update时,如何将null的字段忽略?
    方案如下:
    说明:

    目标源:请求更新的实体数据。
    数据源:通过目标源传上来的id,去数据库中查出的实体数据
    我们可以将目标源中需要改变的属性值过滤掉以后,将数据源中的数据复制到目标源中,这样就达到了,只是更新需要改变的属性值,不需要更新的保持不变。

    工具类如下:

    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.BeanWrapper;
    import org.springframework.beans.BeanWrapperImpl;
    
    import java.beans.PropertyDescriptor;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * There is no royal road to learning.
     * Description:提交实体对象中的null赋值
     * Created by 贤领·周 on 2018年04月10日 15:26
     */
    public class UpdateTool {
        /**
         * 将目标源中不为空的字段过滤,将数据库中查出的数据源复制到提交的目标源中
         *
         * @param source 用id从数据库中查出来的数据源
         * @param target 提交的实体,目标源
         */
        public static void copyNullProperties(Object source, Object target) {
            BeanUtils.copyProperties(source, target, getNoNullProperties(target));
        }
    
        /**
         * @param target 目标源数据
         * @return 将目标源中不为空的字段取出
         */
        private static String[] getNoNullProperties(Object target) {
            BeanWrapper srcBean = new BeanWrapperImpl(target);
            PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
            Set<String> noEmptyName = new HashSet<>();
            for (PropertyDescriptor p : pds) {
                Object value = srcBean.getPropertyValue(p.getName());
                if (value != null) noEmptyName.add(p.getName());
            }
            String[] result = new String[noEmptyName.size()];
            return noEmptyName.toArray(result);
        }
    }
    
  • 相关阅读:
    leetcode35. search Insert Position
    leetcode26.Remove Duplicates from Sorted Array
    leetcode46.Permutation & leetcode47.Permutation II
    leetcode.5 Longest Palindromic Substring
    [转载] C++中new和malloc的区别
    [转载] C++中的自由存储区和堆
    xCode8以及iOS10 的新特性
    cell上添加倒计时,以及时差问题的解决
    cell的复用机制
    iOS 懒加载模式
  • 原文地址:https://www.cnblogs.com/kevliudm/p/11299938.html
Copyright © 2011-2022 走看看