- Product_ 수정
- ProductAPIController
@Slf4j
@RestController
public class ProductAPIController {
@Autowired
private ProductService productService;
.
.
.
.
.
//상품 수정
@PatchMapping("/api/products/{id}")
public ResponseEntity<Product> update(@PathVariable Long id, @RequestBody ProductDto dto) {
Product updated = productService.update(id, dto);
return (updated != null) ?
ResponseEntity.status(HttpStatus.OK).body(updated) :
ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
- ProductService
@Slf4j
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
.
.
.
.
.
@Transactional
public Product update(Long id, ProductDto dto) {
Product product = dto.toEntity();
log.info("id: {}, Product: {}", id, product.toString());
Product target = productRepository.findById(id).orElse(null);
if (target == null || id != product.getId()) {
log.info("잘못된 요청");
return null;
}
target.patch(product);
Product updated = productRepository.save(target);
return updated;
}
}
- Product
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Getter
@Entity
public class Product {
.
.
.
.
.
public void patch(Product product) {
if (product.name != null) {
this.name = product.name;
}
if (product.category != null) {
this.category = product.category;
}
if (product.price != null) {
this.price = product.price;
}
}
}
- Product_ 삭제
- ProductAPIController
@Slf4j
@RestController
public class ProductAPIController {
@Autowired
private ProductService productService;
.
.
.
.
.
//상품 삭제
@DeleteMapping("/api/products/{id}")
public ResponseEntity<Product> delete(@PathVariable Long id) {
Product deleted = productService.delete(id);
return (deleted != null) ?
ResponseEntity.status(HttpStatus.OK).build() :
ResponseEntity.status(HttpStatus.BAD_REQUEST). build();
}
}
- ProductService
@Slf4j
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
.
.
.
.
.
@Transactional
public Product delete(Long id) {
Product target = productRepository.findById(id).orElse(null);
if (target == null) {
return null;
}
productRepository.delete(target);
return target;
}
}
GitHub - Pearlmoon997/CoffeeShop: CoffeeShop
CoffeeShop. Contribute to Pearlmoon997/CoffeeShop development by creating an account on GitHub.
github.com
'프로젝트_ 커피주문 서비스' 카테고리의 다른 글
시간 등록을 위한 JPA Auditing 테스트 (0) | 2022.06.18 |
---|---|
Member_ CRUD (API Controller) (0) | 2022.06.15 |
Product_ Create, Read (API Controller) (0) | 2022.06.14 |
도메인, 엔티티, 테이블 설계 (0) | 2022.06.13 |
개요, 마인드 맵 (0) | 2022.06.09 |