使用JPA更新数据库中的记录的问题 [英] issue with updating record in database using JPA

查看:1450
本文介绍了使用JPA更新数据库中的记录的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有对象,其值如下:

I have object in database with values as follows:


  • id = 1

  • name =john

  • chargeid = 6

我使用merge语句来更新代码
em.merge(obj)

I am using merge statement to update the code em.merge(obj)

当我看到JPA生成的查询时发现在更新查询中只更新了具有新值或非空值的字段。

我检查了与此对象关联的bean,发现在那里没有与chargid相关的注释

I checked the bean which is associated with this object and found that there is no annotations associated with chargid

现在当我尝试更新这个JPA时,如果我没有将anyvalue设置为null,它会得到适当的更新。
现在,如果我设置chargeid = null然后尝试将其设置为db,它会在db中更改为null,但它会将零售值重新设置为先前的值。如何?

Now when i try to update this JPA, it gets properly updated if i don't set anyvalue to null. Now if i set chargeid= null and then try to set persist it into db, it doeskin get changed to null in db but it retails the previous value.How come?

以下是详细信息
1在数据库中有记录如下

The following are the details 1 have record in database as follows

ID     Name   chargeID
1     john      5   

现在,如果我将对象的值设置为

Now if i set values of objects as

obj.setID(1),
obj.setName("johnNew")
obj.setchargID(6)
entinymanager.merge(obj)

然后记录更新如下,这很好

then record is updated as follows, which is fine

Id  name      chargeid
1    johnNew   6

现在如果我想将chargeid设置为null我使用代码

Now if i want to set chargeid to null i use code

obj.setId(1)
obj.setName('XYZ')
obj.setChargeId(null); // i want to update it as null.

现在记录将更新如下

id  name  chargeid
1   XYZ    6        //name is updated to XYZ,but chargeid is not updated to null, how come?


i want to set chargeid to null.


推荐答案

我遇到了同样的问题,因为我创建了一个新的object:

I had the same problem, because I created a new object:

DatabaseObject obj = new DatabaseObject();
obj.setSomeValue(null);
obj.setRowId(1);
entityManager.merge(obj);

我想如果我明确设置了id号,那么如果JPA对象是新的则无关紧要,或具有所需id的现有。也许你做了同样的事情?

I thought if I explicitly set the id number that it wouldn't matter if the JPA object is new, or the existing one with the desired id. Perhaps you did the same?

正确的代码是:

DatabaseObject obj = entityManager.find(DatabaseObject.class, (long) 1);
obj.setSomeValue(null);
obj.setRowId(1);
entityManager.merge(obj);

我希望这有帮助。

这篇关于使用JPA更新数据库中的记录的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆