SpringBoot:Api Ajouter un produit
Les étapes à suivre:
- 1Créer la classe controller PrduitController.java dans le package com.fixwins/controllers et ajouter le repository ProduitRepository
- 2Créer la méthode ajouter() Permettant d'insérer un objet produit dans la table produit puis retourne un message et le status
1.Créer la classe controller PrduitController.java
package com.fixwins.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/*Création du controller de type RestController*/
@RestController
/*la route principale pour consommer l'api du controlleur*/
@RequestMapping("api/produits/")
public class ProduitController {
/*le repository de l'entité produit pour gérer les transaction dans la base de données*/
@Autowired
private ProduitRepository produitRepository;
}
1.Crée la méthode Ajouter()
@PostMapping("/add")
/*@RequestBody :permet de récupéer un objet json puis le convertir à un objet de type produit
{
"id":"5",
"nom":"TV",
"marque":"Sumsung",
"prix":1000,
"qteStock":5
}
*/
public ResponseEntity<Produit> ajouter(@RequestBody Produit produit) {
try {
/*Sauvegarder le produit dans la table produits*/
produitRepository.save(produit);
/*status:201*/
return new ResponseEntity<>(produit, HttpStatus.CREATED);
} catch (Exception e) {
/*Erreur 500*/
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}