当前位置: 移动技术网 > IT编程>开发语言>Java > JPA save()方法将字段更新为null的解决方案

JPA save()方法将字段更新为null的解决方案

2020年03月09日  | 移动技术网IT编程  | 我要评论

徐州中考成绩查询2014,校服的裙摆txt下载,正午的死神

这篇文章主要介绍了jpa save()方法将字段更新为null的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

今天在开发上碰到一个问题,在做页面展示的时候传给前端十个字段,前端修改了其中3个的值,所以只传了3个值给后端,其余字段默认为null,更新后其他7个字段在全部变为了空值。

在前端没法全量回传所有属性的前提下,由后端来处理这类问题。
解决方法:

1.写一个工具方法(updateutil) 用来筛选出所有的空值字段

2.更新时先通过id搜索原始对象,通过findone()等都可以

3.将前端传来的不为空参数(也即是要修改值)copy覆盖原始对象属性值,通过beanutils.copynullproperties(object source, object target)

以下是工具方法:

/**
 * 更新用工具类(忽略为null的字段)
 */
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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网