I have a table Product including about 5 columns: upc, product_name, brand, category, price with upc is the unique value and I set it as Primary Key.
Now I want to update any specific column base on upc, I've already made it done but it always asked to put all column variables into RequestBody although I just want to update one column.
For example, I want to update productName
from Nivea to Dove, I have to use this long RequestBody:
{
"upc": "100101101111",
"productName" : "Dove",
"brand": "Procter & Gamble",
"category" : "Bath and Body",
"description": "Shampoo"
}
If I missed even one key in the RequestBody, I will get the error code 500
. Is it possible if I can just put only 2 columns: upc for specific product that I want to update, and the other column with the value I want to update?
For example, I want to update productName from Nivea to Dove, how can I do like this:
{
"upc": "100101101111",
"productName" : "Dove",
}
Hers is my updateProduct
function:
@Override
public Status updateProduct(Product product) {
List<Product> products = productRepository.findAll();
for (Product prod : products) {
if (prod.getUpc().equals(product.getUpc())) {
productRepository.save(product);
return Status.SUCCESS;
}
}
return Status.PRODUCT_NOT_FOUND;
}
and my controller
:
@PutMapping("/updateproduct")
public ResponseEntity<String> updateProduct(String upc, @RequestBody Product product) {
Status stt = productService.updateProduct(product);
if (stt == Status.SUCCESS) {
return ResponseEntity.status(HttpStatus.OK).body("Product Updated Successfully!");
}
else if (stt == Status.PRODUCT_NOT_FOUND) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Product with upc = " product.getUpc() " Not Found!");
}
else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
CodePudding user response:
Firstly, it is unnecessary to execute a findAll
query as your upc
field is unique, you would be pulling all records for a potentially massive table.
Now here's a potential way to do what you are trying to achieve:
@Override
public Status updateProduct(Product product) {
Product prod = productRepository.findByUpc(product.getUpc());
if (product.getProductName() != null && !Objects.equals(prod.getProductName(), product.getProductName())) {
prod.setProductName(product.getProductName());
productRepository.save(prod);
}
return Status.SUCCESS;
}
You could add multiple if checks and adjust the logic to the fields that you would like the user to be able to update. In this way you are getting the entity from the database and only modifying the fields that the request contains.
Note that if you use this convention for what is being updated, you won't be able to set something to null. It would also be nice to use a DTO
object instead of the same entity class in your requests.