首页 > 技术文章 > JPA-save()方法会将字段更新为null的解决方法

kevliudm 2019-08-04 21:44 原文

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);
    }
}

推荐阅读