Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

动态更新非null字段 #40

Open
zhangzhenhuajack opened this issue Nov 22, 2021 · 0 comments
Open

动态更新非null字段 #40

zhangzhenhuajack opened this issue Nov 22, 2021 · 0 comments

Comments

@zhangzhenhuajack
Copy link
Owner

只更新非null字段

/**

 * @param user

 * @return

 */

@PostMapping("/user/notnull")

public User saveUserNotNullProperties(@RequestBody User user) {

   //数据库里面取出最新的数据,当然了这一步严谨一点可以根据id和version来取数据,如果没取到可以报乐观锁异常

   User userSrc = userRepository.findById(user.getId()).get();

   //将不是null的字段copy到userSrc里面,我们只更新传递了不是null的字段

   PropertyUtils.copyNotNullProperty(user,userSrc);

   return userRepository.save(userSrc);

}

package com.example.jpa.example1.util;



import com.google.common.collect.Sets;

import org.springframework.beans.BeanUtils;

import org.springframework.beans.BeanWrapper;

import org.springframework.beans.BeanWrapperImpl;



import java.util.Set;



public class PropertyUtils {



    /**

     * 只copy非null字段

     *

     * @param source

     * @param dest

     */

    public static void copyNotNullProperty(Object source, Object dest) {

        //利用spring提供的工具类忽略为null的字段

        BeanUtils.copyProperties(source, dest, getNullPropertyNames(source));

    }



    /**

     * get property name that value is null

     *

     * @param source

     * @return

     */

    private static String[] getNullPropertyNames(Object source) {

        final BeanWrapper src = new BeanWrapperImpl(source);

        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();



        Set<String> emptyNames = Sets.newHashSet();

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

    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant