详解Spring Data Jpa当属性为Null也更新的完美解决方案
作者:爱琳琳 发布时间:2022-04-13 03:06:06
开场白
我本来是一名android开发者,突然就对java后端产生了浓烈的兴趣。所以,立马就转到了后端。第一个项目使用的使用Spring Data Jpa来操作数据库的,可是在更新数据的时候发现一个问题,属性值为Null竟然也更新,这就会导致本来没有更新的属性值,全部就成了Null。
原因
经过一番度娘操作,原来Jpa,不知道你是想把属性设置为Null,还是不想。
解决方法
找到一个方法,就是在数据模型上加上注解@DynamicUpdate,可是发现并不好使。而后经过整理,找到以下解决方案
我们有如下实体
@Entity
public class User{
public User(){
}
@Id
@GeneratedValue
public Long id;
private String name;
private String mobileNo;
private String email;
private String password;
private Integer type;
private Date registerTime;
private String region;
private Integer validity;
setter...
getter...
}
需求:我们只更新用户的名字,其他属性值不变。
controller代码如下
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@PostMapping(value = "/save")
public String save(@RequestBody User u) {
userDao.save(u)
return "更新成功";
}
}
注意:如果我们只是更新用户的名字,我们会这样操作,如下只是提交需要更新的用户的id和需要更新属性的值,但是这样的结果就是,其他没有提交更改的属性值,会被当成Null,将数据库中对应值全部设为Null,为了解决这个问题提出以下方案。
{
"id" : "1",
"name" : "张三"
}
方案如下:
说明:
目标源:请求更新的实体数据。
数据源:通过目标源传上来的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);
}
}
这里重点说明一下, BeanUtils.copyProperties这个方法,网上很多教程都是存在误区的,源码如下:
/**
* 通过源码不难看出,该方法就是将source的属性值复制到target中
*
* @param source 数据源(也就是我们通过id去数据库查询出来的数据)
* @param target 目标源(也就是我们请求更新的数据)
* @param ignoreProperties (需要过滤的字段)
*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, (Class)null, ignoreProperties);
}
private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
PropertyDescriptor[] var7 = targetPds;
int var8 = targetPds.length;
for(int var9 = 0; var9 < var8; ++var9) {
PropertyDescriptor targetPd = var7[var9];
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
} catch (Throwable var15) {
throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
}
}
}
}
}
}
有了上面的工具类以后,我们的controller如下写:
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@PostMapping(value = "/save")
public String save(@RequestBody User u) {
if(u.getId != 0){
User source= userDao.findOne(u.getId);
UpdateTool.copyNullProperties(source, u);
}
userDao.save(u)
return "更新成功";
}
}
结果
这样我们更新部分属性值得时候,其他不更新的属性值就不会设置为Null
{
"id" : "1",
"name" : "张三"
}
性能上肯定是有影响,但是目前整理可行的方案,如果有更好的解决方案欢迎留言。
来源:https://blog.csdn.net/zhouxianling233/article/details/79885028


猜你喜欢
- 一个简单的实现版本,没有去Hook键鼠等操作,事先录制好操作步骤(将鼠标移动到需要操作的位置,按下热键执行相应动作),点击运行即可。主要还是
- 引导语上一小节我们学习了 Socket,本文我们来看看服务端套接字 API:ServerSocket,本文学习完毕之后,我们就可以把客户端
- 最近项目中遇到一个问题,在用户没填数据的时候,我们需要接收从前端传过来的对象为null,但是前端说他们一个一个判断特别麻烦,只能传个空对象过
- Android onKeyDown监听返回键无效的解决办法当我们的Activity继承了TabActivity,在该类中重写on
- 本文项目为大家分享了Java实现 * 面五子棋的具体代码,供大家参考,具体内容如下项目介绍:本次设计是基于知识点Java类和对象以及数组开发的
- 在Java中,可以通过Runtime类或ProcessBuilder类来实现调用外部程序。Runtime类与ProcessBuilder类使
- 一、this关键字this是一个引用,它指向自身的这个对象。看内存分析图:假设我们在堆内存new了一个对象,在这个对象里面你想象着他有一个引
- 要求: * 判断用户输入的年份是平年还是闰年实现代码:import java.util.Scanner;/** * 要
- 本文介绍了最好的Java5种遍历HashMap数据的写法,分享给大家,也给自己留一个笔记,具体如下:通过EntrySet的迭代器遍历Iter
- Chart折线图使用鼠标滚轮放大、缩小和平移曲线使用鼠标滚轮滚动放大和缩小X轴的宽度,鼠标左键按住拖动实现曲线的左右平移,不再使用滚动条。添
- 把bitmap图片的某一部分的颜色改成其他颜色private Bitmap ChangeBitmap(Bitmap bitmap){ int
- 介绍最近项目开发中用到了WebView播放视频的功能,总结了开发中犯过的错误,这些错误在开发是及容易遇到的,所以我这里总结了一下,希望大家看
- 委托定义类型,类型指定特定方法签名。可将满足此签名的方法(静态或实例)分配给该类型的变量,然后(使用适当参数)直接调用该方法,或将其作为参数
- 本文实例为大家分享了C#实现钟表程序设计的具体代码,供大家参考,具体内容如下工作空间:代码如下:using System;using Sys
- Hutool Java工具类库_ExcelUtil依赖<!--Hutool Java工具包--> &l
- Activity回顾activity是android程序中最重要的组件之一,它是用户与android用户交互的主要组件,类似于桌面程序的图形
- 1、spring原理内部最核心的就是IOC了,动态注入,让一个对象的创建不用new了,可以自动的生产,这其实就是利用java里的反射,反射其
- 本文实例讲述了C#实现程序开机启动的方法。分享给大家供大家参考,具体如下://此方法把启动项加载到注册表中//获得应用程序路径string
- 一、前言目前 java 垃圾回收主流算法是虚拟机采用 GC Roots Tracing 算法。算法的基本思路是:通过一系列的名为 GC Ro
- 相信大家都遇到过,自己的Java应用运行一段时间就宕机了或者响应请求特别慢。这时候就需要我们了来找出问题所在了。绝大部分都是代码问题导致的。