0

Using Spring framework, trying to do update rest operation, by changing only one attribute in payload

@RequestMapping(value = "/uiv/activeDiscrepancies/{id}", method = RequestMethod.PUT)
public ResponseEntity update(@PathVariable("id") BigInteger id,
                             @RequestBody ActiveDiscrepancies activeDiscrepancy)
                   throws SureException{

    //ActiveDiscrepancies adiscrepancies =  
    activeDiscrepancyRepo.save(activeDiscrepancy, id);

    ActiveDiscrepancies adiscrepancies = activeDiscrepancyRepo.findByActiveDiscrepancyId(id); 
    activeDiscrepancy.setActiveDiscrepancyId( adiscrepancies.getActiveDiscrepancyId() );
    activeDiscrepancyRepo.save(activeDiscrepancy);
}

But update query fired is

Hibernate:

update ACTIVE_DISCREPANCIES 
   set ACTIVE_DISCREPANCY_NAME=?, AUDITED_ENTITY=?, CREATION_TIME=?, 
       DELTA_TYPE=?, DISCREPANCY=?, EXPIRY_TIME=?, LAST_UPDATED_TIME=?, 
       MESSAGE_KEY=?, NETWORK=?, RECON_REASON=?, RECON_TYPE=?, 
       REMARKS=?, RESOURCE_LABEL=?, STATUS=? 
 where ACTIVE_DISCREPANCY_ID=?

So for other columns is replaced with null values, how to solve this problem?

Jorge Campos
  • 22,647
  • 7
  • 56
  • 87
  • I assume the entity `activeDiscrepancy` which is passed into the method already contains the null values? You probably should load the entity from the DB first and then only copy non null values to the loaded entity and save that one. – cmoetzing Apr 15 '19 at 07:02
  • Instead of re-saving the updated object try to update it directly via SQL query from repository interface. – Σωτήρης Ραφαήλ Apr 15 '19 at 08:15
  • 1
    Your problem is not about the PUT request, but on your Hibernate. When facing this situation usually I have two options. First, from the client you need to send complete object with updated data, it's mean you need to populate the id and the missing null data from client. Second, you retrieve the data by Id from the back-end, and with this object you make a conditional if the value is not equals then update the field with new data – Sukma Wardana Apr 15 '19 at 09:54

1 Answers1

1

First of all, PUT methods are meant to receive and update the whole entity. For partial updates PATCH method is preferred. You can read more about that here.

If you wish to update the entire entity, then you should send the entire entity in your request body. If not, then you should fetch the entity from db by id, apply your changes accordingly and save it. save method in Spring Data repos would replace the entire entity.

Nima Ajdari
  • 2,754
  • 2
  • 14
  • 18