Partage
  • Partager sur Facebook
  • Partager sur Twitter

Spring Boot PatchMapping

RequestBody entièrement rempli avec int et float à 0

Sujet résolu
    9 avril 2024 à 17:39:41

    Bonjour,

    Voilà, j'ai un petit problème avec mon contrôleur PatchMapping que voici :

    /**
    	 * Update - Update an existing product
    	 *
    	 * @param id		- The id of the product to update
    	 * @param employee 	- The product object to update
    	 * @return The product object updated
    	 * @throws IllegalAccessException 
    	 * @throws IllegalArgumentException 
    	 */
    	@PatchMapping("/products/{id}")
    	public ResponseEntity<Product> updateProduct(@PathVariable("id") final Long id, @RequestBody final Product product) throws IllegalArgumentException, IllegalAccessException {
    		final Optional<Product> receivedProduct = productService.getProduct(id);
    		if (receivedProduct.isPresent()) {
    			// Get the received product and update non null fields
    			Product existingProduct = receivedProduct.get();			
    	        Class<?> productClass = Product.class;
    	        Field[] productFields = productClass.getDeclaredFields();
    	        for (Field field : productFields) {
    	            field.setAccessible(true);
    	            Object value = field.get(product);
                	if (value != null) {
    	                field.set(existingProduct, value);
    	            }
    	            field.setAccessible(false);
    	        }
    			// Save the product with the new properties
    			Product productSaved = productService.saveProduct(existingProduct);
    			return new ResponseEntity<Product>(productSaved, HttpStatus.ACCEPTED);
    		} else {
    			throw new ProductNotFoundException("Product with id " + id + " not found.");
    		}
    	}

    Je sais que le PATCH n'est pas fait pour ça mais voilà ce qui est demandé dans l'énoncé d'un test technique (de mettre à jour les détails d'un produit s'il existe) :

    | Resource           | POST                  | GET                            | PATCH                                    | PUT | DELETE           |
    | ------------------ | --------------------- | ------------------------------ | ---------------------------------------- | --- | ---------------- |
    | **/products**      | Create a new products | Retrieve all products          | X                                        | X   |     X            |
    | **/products/1**    | X                     | Retrieve details for product 1 | Update details of product 1 if it exists | X   | Remove product 1 |

    Je me suis donc exécuté avec le code Java que je vous ai transmis.

    Lorsque que je fais ma requête PTACH "/products/1" avec Postman de cette manière (avec seulement le propriété name) :

    {
        "name": "name1"
    }

    Voilà ce que j'obtiens dans mon objet RequestBody :

    Object RequestBody

    Mes propriétés String sont bien à null mais les int et les float sont à 0.

    Du coup, ces propriétés sont mise à jour également alors que ce n'est pas ce que je souhaite.

    Quelqu'un aurait-il idée de parer à ce problème ?

    Merci d'avance et bonne fin de journée

    • Partager sur Facebook
    • Partager sur Twitter
      10 avril 2024 à 18:17:37

      Pour ceux qui auraient le même soucis :


      /**
      	 * Update - Update an existing product
      	 *
      	 * @param id		- The id of the product to update
      	 * @param employee 	- The product object to update
      	 * @return The product object updated
      	 * @throws IllegalAccessException 
      	 * @throws IllegalArgumentException 
      	 */
      	@PatchMapping("/products/{id}")
      	public ResponseEntity<Product> updateProduct(@PathVariable("id") final Long id, @RequestBody final Map<Object, Object> fields) throws IllegalArgumentException, IllegalAccessException {
      		final Optional<Product> receivedProduct = productService.getProduct(id);
      		if (receivedProduct.isPresent()) {
      			Product product = receivedProduct.get();
      			// Get the received keys/values and update the product
      			fields.forEach((key, value) -> {
      				Field field = ReflectionUtils.findField(Product.class, (String) key);
      				field.setAccessible(true);
      				ReflectionUtils.setField(field, product, value);
      				field.setAccessible(false);
      			});
      			// Save the product with the new properties
      			Product productSaved = productService.saveProduct(product);
      			return new ResponseEntity<>(productSaved, HttpStatus.OK);
      		} else {
      			throw new ProductNotFoundException("Product with id " + id + " not found.");
      		}
      	}
      • Partager sur Facebook
      • Partager sur Twitter

      Spring Boot PatchMapping

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      • Editeur
      • Markdown