zl程序教程

您现在的位置是:首页 >  后端

当前栏目

对象的复制

对象 复制
2023-09-11 14:15:07 时间

通常我们在更新操作的时候,往往对于一些现有的数据比如is_delete 和 create_time 等。这些字段不行该覆盖更新,所以我们通常把需要修改的的对象从数据库查询出来
然后再进行更新操作。
spring给我们提供的有beanUtils工具类。功能很强大。后面跟的是可以忽略的字段

BeanUtils.copyProperties(dataTemplateDto,dataTemplate,"isDelete","createTime","vid");
BeanUtils.copyProperties(dataTemplateDto,dataTemplateField,"isDelete","createTime","vid");

 

也可以用这个工具类

package com.mairuide._frame.utils;


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;
/**
 * Created by 敲代码的卡卡罗特
 * on 2018/11/29 19:55.
 */

public class UpdateTool {
    /**
     * 将目标源中不为空的字段过滤,将数据库中查出的数据源复制到提交的目标源中
     * 目标源:请求更新的实体数据。
     * 数据源:通过目标源传上来的id,去数据库中查出的实体数据
     *
     * @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);
    }
}