I want to write a function that will update products freely.
But in the second update I get an error:
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [guru.springframework.domain.Product#4]
the code in the controller :
@ApiOperation(value = "Update a product")
@RequestMapping(value = "/update/", method = RequestMethod.PUT, produces = "application/json")
public ResponseEntity<EntityModel<Product>> updateProduct(@RequestBody Product product){
return productService.updateProduct(product);
}
the code in the ServiceImpl :
@Override
public ResponseEntity<EntityModel<Product>> updateProduct(Product product) {
boolean exist=productRepository.existsById(product.getProductId());
if(exist){
productRepository.save(product);
return ResponseEntity.ok().body(productEntityFactory.toModel(product));
}else {
throw new EntityNotFoundException("There is no product with the given ID, so it can't be updated");
}
}
if the sent json does not undergo any change, then you can send it as many as you want, but if there is a change, it will only work for the first time.
You have to flush your change. Because otherwise you leave the change from the first request 'open'. Just use productRepository.saveAndFlush(product);
Instead of productRepository.save(product);
This should work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.