JPA database record update release

I have an object in a database with values ​​as follows:

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

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

When I see a query generated by JPA, I find that only fields with new or non-zero values ​​are updated in updates.

I checked the bean that is associated with this object and found that there are no comments related to the charge

Now when I try to update this JPA, it gets a proper update if I do not set anyvalue to null. Now, if I set chargeid = null and then try to set it to db, it will be changed to null in db, but it keeps the same value. How did it happen?

The following details 1 have an entry in the database as follows

 ID Name chargeID 1 john 5 

Now, if I set the values ​​of objects as

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

then the record is updated as follows:

 Id name chargeid 1 johnNew 6 

Now, if I want to set chargeid to null, I use the 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. 
+2
java jpa
source share
4 answers

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 that if I explicitly set the identifier number, it does not matter if the JPA object is new or existing with the desired identifier. Did you do the same?

The correct code is:

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

Hope this helps.

+1
source share

Perhaps you have a "non null" for the chargeid column? (In your database)

0
source share

Another way to do this is to set the object to NULL after executing the merge method, as shown below:

 obj.setchargID(6) obj = entinymanager.merge(obj) obj.setchargID(null) 
0
source share

Please follow these steps. values ​​that are not explicitly set are automatically set to zero.

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

he will work.

0
source share

All Articles