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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM