|
| 1 | +package com.ecars.microcars.controller; |
| 2 | + |
| 3 | +import com.ecars.microcars.dao.CarDao; |
| 4 | +import com.ecars.microcars.model.Car; |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.http.HttpStatus; |
| 7 | +import org.springframework.http.ResponseEntity; |
| 8 | +import org.springframework.web.bind.annotation.*; |
| 9 | + |
| 10 | +import javax.sql.rowset.CachedRowSet; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +@RestController |
| 14 | +public class CarController { |
| 15 | + |
| 16 | + @Autowired //Instanciation automatique |
| 17 | + private CarDao carDao; |
| 18 | + |
| 19 | + //INDEX => /cars |
| 20 | + @GetMapping(value = "cars") //GET Mapping pour l'uri pour la liste des voitures |
| 21 | + public List<Car> listCars() { |
| 22 | + return carDao.findAll(); |
| 23 | + } |
| 24 | + |
| 25 | + //SHOW BY ID => /cars/{id} |
| 26 | + @GetMapping(value = "cars/{id}") //GET Mapping pour l'uri pour retourner une voiture par l'id |
| 27 | + public Car showCar(@PathVariable int id) {// Va chercher le paramètre id dans l'url et le passe à notre méthode |
| 28 | + return carDao.findById(id); |
| 29 | + } |
| 30 | + |
| 31 | + //STORE /cars |
| 32 | + @PostMapping(value = "cars") |
| 33 | + public void storeCar(@RequestBody Car car) { // Aller chercher dans le body de la requête la voiture et le parser |
| 34 | + carDao.save(car); |
| 35 | + } |
| 36 | + |
| 37 | + @PutMapping(value = "/cars/{id}") |
| 38 | + public ResponseEntity<?> updateCar(@PathVariable("id") int id, @RequestBody Car car) { |
| 39 | + Car currentCar = carDao.findById(id); |
| 40 | + currentCar.setBrand(car.getBrand()); |
| 41 | + currentCar.setModel(car.getModel()); |
| 42 | + carDao.updateCar(currentCar); |
| 43 | + return new ResponseEntity<Car>(currentCar, HttpStatus.OK); |
| 44 | + } |
| 45 | + |
| 46 | + //DELETE |
| 47 | + @DeleteMapping (value = "/cars/{id}") |
| 48 | + public void deleteCar(@PathVariable int id) { |
| 49 | + carDao.deleteCar(id); |
| 50 | + } |
| 51 | +} |
0 commit comments