Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4주차 과제- 고양이 장난감가게 만들기 #76

Merged
merged 33 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
f7d8b9e
기본 작성
jdalma Aug 22, 2022
18cc4b3
DB 연동
jdalma Aug 23, 2022
16c5fd5
계층 이름 수정
jdalma Aug 23, 2022
f62d9be
Service findAll 메소드 테스트 작성
jdalma Aug 23, 2022
22f4dd8
ResourceNotFoundException 커스텀 예외 추가
jdalma Aug 23, 2022
e0ce4a1
Advice , ErrorResult 추가
jdalma Aug 23, 2022
b3bb1f1
ProductService findById메서드 테스트 작성
jdalma Aug 23, 2022
bd99da7
Update app/src/test/java/com/codesoom/assignment/application/ProductS…
jdalma Aug 24, 2022
66c4118
메서드 네이밍 수정 newProduct
jdalma Aug 24, 2022
3430a2c
ProductService 주석 추가
jdalma Aug 24, 2022
12102bd
JPA ddl-auto : create로 수정
jdalma Aug 24, 2022
2acf43a
Product DTO 추가
jdalma Aug 24, 2022
ab8d812
NullResourceException 커스텀 예외 추가
jdalma Aug 24, 2022
591eb17
ProductDTO 추가
jdalma Aug 24, 2022
136e58b
BadRequestException 커스텀 예외 추가
jdalma Aug 24, 2022
cf3c24c
ProductService save 메서드 테스트 추가
jdalma Aug 24, 2022
f9947fd
필요없는 import 삭제
jdalma Aug 24, 2022
275e607
ProductController 테스트 추가
jdalma Aug 24, 2022
d84bf20
NullResourceException 삭제
jdalma Aug 25, 2022
b728d01
'@Transactional(readOnly = true)' 설정
jdalma Aug 25, 2022
161d33c
Setter 추가
jdalma Aug 26, 2022
85c0854
update 메서드 적용
jdalma Aug 26, 2022
ec0ab94
ProductService 조회 기능 메서드 분리
jdalma Aug 26, 2022
9752bad
application 패키지 service로 변경
jdalma Aug 26, 2022
370d4c5
ProductServiceDI Repository 주입받아서 테스트
jdalma Aug 26, 2022
a3e4bb5
ProductControllerTest Service 기능 분리
jdalma Aug 26, 2022
be1afbc
Product Setter 제거
jdalma Aug 27, 2022
acb2e00
findAll 메서드 불필요한 형변환 제거
jdalma Aug 27, 2022
9e7514a
findAll메서드 반환 타입 주석 수정
jdalma Aug 27, 2022
e6b26cb
deleteById 테스트 코드 추가
jdalma Aug 27, 2022
e93c0ef
Optional map 사용
jdalma Aug 28, 2022
969de04
테스트 추가
jdalma Aug 28, 2022
2f12058
Update app/src/main/java/com/codesoom/assignment/service/ProductServi…
jdalma Aug 28, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.codesoom.assignment.controller;

import com.codesoom.assignment.dto.ProductDTO;
import com.codesoom.assignment.service.ProductSearchService;
import com.codesoom.assignment.service.ProductService;
import com.codesoom.assignment.domain.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/products")
public class ProductController {

private final ProductService service;
private final ProductSearchService searchService;

public ProductController(ProductService service , ProductSearchService searchService) {
this.service = service;
this.searchService = searchService;
}

@GetMapping
public Iterable<Product> findAllProduct(){
return searchService.findAll();
}

@GetMapping("{id}")
public Product findProduct(@PathVariable Long id){
return searchService.findById(id);
}

@PostMapping
public Product createProduct(@RequestBody ProductDTO productDTO) {
return service.save(productDTO.toProduct());
}

@PatchMapping("{id}")
public Product updateProduct(@PathVariable Long id,
@RequestBody Product product){
return service.update(id , product);
}

@DeleteMapping("{id}")
public void deleteProduct(@PathVariable Long id){
service.deleteById(id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.codesoom.assignment.controller;

import com.codesoom.assignment.dto.ErrorResult;
import com.codesoom.assignment.exception.ResourceNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice(basePackageClasses = ProductController.class)
public class ProductControllerAdvice {

@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public ErrorResult resourceNotFound(ResourceNotFoundException e){
return new ErrorResult(e.getMessage());
}
}
37 changes: 37 additions & 0 deletions app/src/main/java/com/codesoom/assignment/domain/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.codesoom.assignment.domain;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Getter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class Product {

@Id
@GeneratedValue
private Long id;

private String name;
private String maker;
private int price;
private String fileName;

public Product updateProduct(Product update){
this.name = update.getName();
this.maker = update.getMaker();
this.price = update.getPrice();
this.fileName = update.getFileName();
return this;
}
}
13 changes: 13 additions & 0 deletions app/src/main/java/com/codesoom/assignment/dto/ErrorResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.codesoom.assignment.dto;


import lombok.Getter;

@Getter
public class ErrorResult {
private final String message;

public ErrorResult(String message) {
this.message = message;
}
}
35 changes: 35 additions & 0 deletions app/src/main/java/com/codesoom/assignment/dto/ProductDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.codesoom.assignment.dto;

import com.codesoom.assignment.domain.Product;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.ToString;

import javax.validation.constraints.NotNull;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

591eb17 커밋의 제목과 실제 한 일이 달라요! 또한 @NotNull 은 사용하지 않는 것처럼 보이네요!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

커밋 제목 , import 부분 신경쓰도록 하겠습니다 ㅎㅎ



@ToString
@Getter
public class ProductDTO {

private final String name;
private final String maker;
private final int price;
private final String fileName;

@JsonCreator
public ProductDTO(@JsonProperty("name") String name,
@JsonProperty("maker") String maker,
@JsonProperty("price") int price,
@JsonProperty("fileName") String fileName) {
this.name = name;
this.maker = maker;
this.price = price;
this.fileName = fileName;
}

public Product toProduct(){
return new Product(null , this.name , this.maker , this.price , this.fileName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.codesoom.assignment.exception;

public class BadRequestException extends RuntimeException{
public BadRequestException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.codesoom.assignment.exception;

public class ResourceNotFoundException extends RuntimeException{
public ResourceNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.codesoom.assignment.repository;

import com.codesoom.assignment.domain.Product;
import org.springframework.data.repository.CrudRepository;

public interface ProductJPARepository
extends CrudRepository<Product, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.codesoom.assignment.service;

import com.codesoom.assignment.domain.Product;
import com.codesoom.assignment.exception.ResourceNotFoundException;
import com.codesoom.assignment.repository.ProductJPARepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
@AllArgsConstructor
public class ProductSearchService {

private final ProductJPARepository repository;

/**
* 모든 엔티티를 반환합니다
*
* @return Iterable<엔티티>
*/
public Iterable<Product> findAll(){
return repository.findAll();
}

/**
* 식별자와 같은 엔티티를 찾아 반환합니다
*
* @param id
* @return id에 해당하는 자원
* @throws ResourceNotFoundException
* id에 해당하는 자원이 존재하지 않을 때 던져진다
*/
public Product findById(Long id){
return repository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("상품이 존재하지 않습니다. id : " + id));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.codesoom.assignment.service;

import com.codesoom.assignment.domain.Product;
import com.codesoom.assignment.exception.ResourceNotFoundException;
import com.codesoom.assignment.repository.ProductJPARepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Transactional 어노테이션이 붙었군요!
이 기능은 모든 메소드에 필요한 기능일까요?

Copy link
Author

@jdalma jdalma Aug 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

내일 조사하고 수정해보겠습니다!


@Transactional(readOnly = true)를 달면 최적화가 된다고만 알고 있었어서 JPA에서 최적화가 어떻게 되는건지 공식 문서에서 찾을려고 했는데.. 못 찾았네요 ㅎㅎ 계속 조사해보겠습니다

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Transactional 어노테이션 관련 공식 도큐먼트를 읽어보는 것이 시작이 될 것 같아요!

public class ProductService{

private final ProductJPARepository repository;

public ProductService(ProductJPARepository repository) {
this.repository = repository;
}

/**
* 주어진 엔티티를 저장합니다
*
* @param product
* @return 저장된 product
*/
public Product save(Product product){
return repository.save(product);
}

/**
* id에 해당하는 엔티티의 정보를 넘겨받은 엔티티로 대체한다
* id는 변경되지 않는다
* @param id 엔티티의 식별자
* @param product 대체할 엔티티의 정보
* @return 수정된 product
*/
public Product update(Long id , Product product){
Optional<Product> optionalProduct = repository.findById(id);
optionalProduct
.orElseThrow(() -> new ResourceNotFoundException("상품이 존재하지 않습니다. id : " + id));
return optionalProduct.map(p -> p.updateProduct(product)).get();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Optional<Product> optionalProduct = repository.findById(id);
optionalProduct
.orElseThrow(() -> new ResourceNotFoundException("상품이 존재하지 않습니다. id : " + id));
return optionalProduct.map(p -> p.updateProduct(product)).get();
return repository
.findById(id);
.map(p -> p.updateProduct(product))
.orElseThrow(() -> new ResourceNotFoundException("상품이 존재하지 않습니다. id : " + id));

제가 생각한 체이닝은 이런 느낌이에요!

}

/**
* id에 해당하는 엔티티를 삭제한다
* @param id 엔티티의 식별자
*/
public void deleteById(Long id){
repository.deleteById(id);
}
}
2 changes: 1 addition & 1 deletion app/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ spring:
url: jdbc:h2:~/data/demo
jpa:
hibernate:
ddl-auto: update
ddl-auto: create