Created
July 28, 2023 21:39
-
-
Save andersonFaro9/44bdcd9aceb1fb12243f62b181127465 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.crud.controllers; | |
import com.example.crud.domain.product.Product; | |
import com.example.crud.domain.product.ProductRepository; | |
import com.example.crud.domain.product.RequestProductDTO; | |
import jakarta.persistence.EntityNotFoundException; | |
import jakarta.validation.Valid; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.transaction.annotation.Transactional; | |
import org.springframework.web.bind.annotation.*; | |
import java.util.Optional; | |
import static org.springframework.data.jpa.domain.AbstractPersistable_.id; | |
@RestController | |
@RequestMapping("/product") | |
public class ProductController { | |
@Autowired | |
private ProductRepository repository; | |
@GetMapping | |
public ResponseEntity getAllProducts(){ | |
var allProducts = repository.findAll(); | |
return ResponseEntity.ok(allProducts); | |
} | |
@PostMapping | |
public ResponseEntity register(@RequestBody @Valid RequestProductDTO data) { | |
Product newProduct = new Product(data); | |
repository.save(newProduct); | |
return ResponseEntity.ok().build(); | |
} | |
@PutMapping | |
@Transactional | |
public ResponseEntity updateProduct (@RequestBody @Valid RequestProductDTO data) { | |
Optional<Product> optionalProduct = repository.findById(data.id()); | |
if (optionalProduct.isPresent()) { | |
Product product = optionalProduct.get(); | |
product.setName(data.name()); | |
product.setPrice_in_cents(data.price_in_cents()); | |
return ResponseEntity.ok(product); | |
} else { | |
return ResponseEntity.notFound().build(); | |
} | |
@DeleteMapping(value = "/{id}") | |
public ResponseEntity deleteProduct(@PathVariable String id){ | |
Optional<Product> optionalProduct = repository.findById(id); | |
if (optionalProduct.isPresent()) { | |
Product product = optionalProduct.get(); | |
product.setActive(false); | |
return ResponseEntity.noContent().build(); | |
} else { | |
throw new EntityNotFoundException(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment