작성
·
437
2
상속 받은 엔티티는 @Builder를 사용하는게 아니라, 다음과 같이 @SuperBuilder로 자식, 부모 엔티티 모두에 선언해줘야 한다고 합니다.
<Book 엔티티>
package jpabook.jpashop.domain.item;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
@Entity
@DiscriminatorValue("B")
@Getter
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class Book extends Item {
private String isbn;
private String author;
}
<Item 엔티티>
package jpabook.jpashop.domain.item;
import jakarta.persistence.*;
import jpabook.jpashop.domain.Category;
import jpabook.jpashop.exception.NotEnoughStockException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Item{
@Id
@GeneratedValue
@Column(name = "ITEM_ID")
private Long id;
private String name;
private int price;
private int stockQuantity;
@ManyToMany(mappedBy = "items")
private List<Category> categories = new ArrayList<>();
/*비즈니스 로직*/
//todo: stock 증가
public void addStock(int quantity) {
this.stockQuantity += quantity;
}
//todo: stock 감소
public void removeStock(int quantity) {
int restStock = this.stockQuantity - quantity;
if (restStock < 0) {
throw new NotEnoughStockException("need more stock");
}
this.stockQuantity = restStock;
}
}
<ItemController 클래스>
package jpabook.jpashop.controller;
import jakarta.validation.Valid;
import jpabook.jpashop.domain.item.Book;
import jpabook.jpashop.service.ItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
@RequiredArgsConstructor
public class ItemController {
private final ItemService itemService;
@GetMapping("/items/new")
public String createForm(Model model) {
model.addAttribute("form", new BookForm());
return "items/createItemForm";
}
@PostMapping("/items/new")
public String create(@Valid @ModelAttribute("form") BookForm form, BindingResult result) {
if (result.hasErrors()) {
return "items/createItemForm";
}
Book book = createBook(form);
itemService.saveItem(book);
return "redirect:/";
}
//todo: dto 정보를 받아서 엔티티를 만드는 단순 작업은 컨트롤러에서 처리
private Book createBook(BookForm form) {
return Book.builder()
.name(form.getName())
.price(form.getPrice())
.stockQuantity(form.getStockQuantity())
.author(form.getAuthor())
.isbn(form.getIsbn())
.build();
}
}
이렇게 하고, Jpashop의 상품등록에 들어가서 데이터를 입력하면 정상적으로 DB에 데이터가 저장됩니다.