java jpa save方法辅助工具类

3 篇文章 0 订阅

java jpa save方法更新数据工具类

  • 因为jpa没有单独更新某些字段的方法,save方法可以更新某条数据,但是有一个缺陷,就是它会将为空的字段也更新上去.
    如果有一个工具类可以将一个实体类非空的数据映射到jpa的findOne数据上,再进行save,就会方便很多.如下:

import com.alibaba.druid.util.StringUtils;
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.Objects;
import java.util.Set;

public class UpdateUtil {
    /**
     * 所有为空值的属性都不copy
     *
     * @param source
     * @param target
     */
    public static void copyNullProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullField(source));
    }

    /**
     * 获取属性中为空的字段
     *
     * @param target
     * @return
     */
    private static String[] getNullField(Object target) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(target);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        Set<String> notNullFieldSet = new HashSet<>();
        if (propertyDescriptors.length > 0) {
            for (PropertyDescriptor p : propertyDescriptors) {
                String name = p.getName();
                Object value = beanWrapper.getPropertyValue(name);
                if (Objects.isNull(value)) {
                    notNullFieldSet.add(name);
                }
            }
        }
        String[] notNullField = new String[notNullFieldSet.size()];
        return notNullFieldSet.toArray(notNullField);
    }

    public static void main(String[] args) {
        IdNameVo newvo=  new IdNameVo();
        newvo.setId("1");
        newvo.setName("更新后的实体类");
        newvo.setLevel(1);
        newvo.setParentId("0");
        IdNameVo old=  new IdNameVo();
        old.setId("1");
        old.setName("更新前的实体类");
        old.setLevel(2);
        old.setParentId("1");
        old.setIdx(4);
        old.setCode("123");
        System.out.println(old);
        UpdateUtil.copyNullProperties(newvo,old);
        System.out.println(old);
		//然后直接jpa的save(vo2)就可以了
    }
}

输出的结果为:

IdNameVo(id=1, name=更新前的实体类, parentId=1, level=2, idx=4, children=[],code=123, coupon=null, couponId=null, promotionId=null,
promotionType=null, searchType=null)
IdNameVo(id=1, name=更新后的实体类, parentId=0, level=1, idx=4, children=[], code=123, coupon=null, couponId=null, promotionId=null,
promotionType=null, searchType=null)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值