详解Spring Data Jpa当属性为Null也更新的完美解决方案

2025-05-29 0 53

开场白

我本来是一名android开发者,突然就对java后端产生了浓烈的兴趣。所以,立马就转到了后端。第一个项目使用的使用spring data jpa来操作数据库的,可是在更新数据的时候发现一个问题,属性值为null竟然也更新,这就会导致本来没有更新的属性值,全部就成了null。

原因

经过一番度娘操作,原来jpa,不知道你是想把属性设置为null,还是不想。

解决方法

找到一个方法,就是在数据模型上加上注解@dynamicupdate,可是发现并不好使。而后经过整理,找到以下解决方案

我们有如下实体

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
@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代码如下

?

1

2

3

4

5

6

7

8

9

10

11
@restcontroller

public class usercontroller {

@autowired

private userdao userdao;

@postmapping(value = "/save")

public string save(@requestbody user u) {

userdao.save(u)

return "更新成功";

}

}

注意:如果我们只是更新用户的名字,我们会这样操作,如下只是提交需要更新的用户的id和需要更新属性的值,但是这样的结果就是,其他没有提交更改的属性值,会被当成null,将数据库中对应值全部设为null,为了解决这个问题提出以下方案。

?

1

2

3

4
{

"id" : "1",

"name" : "张三"

}

方案如下:

说明:

  1. 目标源:请求更新的实体数据。
  2. 数据源:通过目标源传上来的id,去数据库中查出的实体数据

我们可以将目标源中需要改变的属性值过滤掉以后,将数据源中的数据复制到目标源中,这样就达到了,只是更新需要改变的属性值,不需要更新的保持不变。

工具类如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40
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这个方法,网上很多教程都是存在误区的,源码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57
/**

* 通过源码不难看出,该方法就是将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如下写:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
@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

?

1

2

3

4
{

"id" : "1",

"name" : "张三"

}

性能上肯定是有影响,但是目前整理可行的方案,如果有更好的解决方案欢迎留言。

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

原文链接:https://blog.csdn.net/zhouxianling233/article/details/79885028

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解Spring Data Jpa当属性为Null也更新的完美解决方案 https://www.kuaiidc.com/109658.html

相关文章

发表评论
暂无评论