Spring 브랜드콘 클론2

춤인형의 개발일지·2025년 1월 2일

Spring실습

목록 보기
20/40

25/1/2(목)

브랜드콘 클론

Product 수정

❗1:N의 관계에서 N이 1의 직접적인 정보를 가지고 있으면 안된다.

아래의 수정된 것을 살펴보자

//기존 product Entity
@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String brandName; //brandName은 없어야함
    private String productName;
    private int price;
    private String imageUrl;
    private int expirationDays;
    
    @ManyToOne
    private Brand brand;
    
//수정 후 Entity
@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String productName;
    private int price;
    private String imageUrl;
    private int expirationDays;
    
    @ManyToOne
    private Brand brand;

product는 brand를 참조하고 있다. brand에는 brand의 name이 Entity의 객체로 가지고 있다. 따라서 product에 직접적으로 brandName을 주지 않아도, brand를 참조해서(.을 찍어서) 사용해야한다.

//수정 전
private List<ProductResponse> allProduct() {
        List<Product> all = productRepository.findAll();
        return all.stream().map(product -> new ProductResponse(
                product.getId(),
                product.getBrandName(), // 여기를 보세요
                product.getProductName(),
                product.getPrice(),
                product.getImageUrl()
        )).toList();
    }

private List<ProductResponse> allProduct() {
        List<Product> all = productRepository.findAll();
        return all.stream().map(product -> new ProductResponse(
                product.getId(),
                product.getBrand().getName(), //여기를 보세요
                product.getProductName(),
                product.getPrice(),
                product.getImageUrl()
        )).toList();
    }

product.getBrandName() 으로 받았던 것을 product.getBrand().getName() 이렇게 getBrand로 참조한 후의 그것의 name을 받을 수있도록 수정해줘야한다.


😐 느낀점

참조한다고 끝. 이 아니라, 그것을 활용해서 그 안의 정보들을 활용할 수 있도록한다. 
그래야 프론트에서 더 많은 정보들을 주지 않아도 알아서 자동으로 들어갈 수 있기 때문에 더 좋은 방법이다.

0개의 댓글