开发者

issue with updating record in database using JPA

I have object in database with values as follows:

  • id =1
  • name = "john"
  • chargeid = 6

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

When i see the query generated by JPA i found that in update query only fields which has new or not null values are updated.

I checked开发者_StackOverflow社区 the bean which is associated with this object and found that there is no annotations associated with chargid

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?

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

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.

Now the record will be updated as follows

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.


Another option to do that is set the object as NULL after the merge method execution like below:

obj.setchargID(6)
obj = entinymanager.merge(obj)
obj.setchargID(null)


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

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

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?

The correct code is:

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

I hope this helps.


Perhaps you have an 'not null' defined for the chargeid column? (In your database)


Please follow the steps below. values which are not set explicitly will set to null automatically.

obj.setId(1);
obj.setName('XYZ');
entinymanager.merge(obj);

it will work..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜