Reputation: 1893
I have object in database with values as follows:
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 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.
Upvotes: 3
Views: 7241
Reputation: 623
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.
Upvotes: 1
Reputation: 150
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..
Upvotes: 0
Reputation: 184
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)
Upvotes: 1
Reputation: 2993
Perhaps you have an 'not null' defined for the chargeid column? (In your database)
Upvotes: 0