spring-data-jpa 中save()方法会将不需要更新字段更新为null的解决方法
最近刚刚接触jpa 这个框架,发现他在处理数据方面确实是比较快,但是在一些条件判断方面却没有mybatis灵活,就我最近遇到的一个问题以及解决方案做下总结
Spring data jpa使用save方法update时,如何将null的字段忽略?
方案如下:
说明:
目标源:请求更新的实体数据。
数据源:通过目标源传上来的id,去数据库中查出的实体数据
我们可以将目标源中需要改变的属性值过滤掉以后,将数据源中的数据复制到目标源中,这样就达到了,只是更新需要改变的属性值,不需要更新的保持不变。
工具类如下:
package com.yunmai.kangya.core;
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;
/**
作用:用来实体对象中的null赋值
名称:UpdateUtil
时间:2020-8-27
作者:pq
/
public class UpdateUtil {
/*将目标源中不为空的字段过滤,将数据库中查出的数据源复制到提交的目标源中
*@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> emptyName=new HashSet<>();
for(PropertyDescriptor p:pds){Object srcValue=srcBean.getPropertyValue(p.getName()); if(srcValue!=null) emptyName.add(p.getName());
}
String[] result=new String[emptyName.size()];
return emptyName.toArray(result);
}
}
然后我调用接口测试了一波,结果测试成功代码如下:
/**添加或修改富文本信息
*/
@PostMapping(“/addOrUpdRichInfo”)
public Result addOrUpd(@RequestBody SystemRichTextConfig sysRichTextConfig, LoginUser loginUser) {
if(sysRichTextConfig.getId() !=null){ //如果有id 就是修改,没有就是新增SystemRichTextConfig systemRichTextConfig = sysRichTextDao.findById(sysRichTextConfig.getId()).orElse(null); UpdateUtil.copyNullProperties(systemRichTextConfig,sysRichTextConfig);
}
SystemRichTextConfig richTextConfig = sysRichTextDao.save(sysRichTextConfig);
return Result.success();
}
总结:最后结合自身框架和前端框架反思了一下,目前前端流行框架为vue,如果是数据呈现列表展示,如果只展示单表数据的话其实也可以不用工具类,因为vue能渲染列表,通过循环item 拿到单行所有数据,但是遇到多表联查的情况是肯定需要进行null值处理的,实际业务中一般列表展示单表数据展示出现的也比较少!