소개
게시글
질문&답변
2024.09.23
상품 수정시 기존값이 그대로 유지되어 나타나요
ItemControllerpackage jpabook.jpashop.controller; import jakarta.validation.Valid; import jpabook.jpashop.domain.Item.Book; import jpabook.jpashop.domain.Item.Item; 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.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; @Controller @RequiredArgsConstructor public class ItemController { private final ItemService itemService; @GetMapping("/items/new") public String createForm(Model model) { model.addAttribute("bookForm", new BookForm()); return "items/createItemForm"; } @PostMapping("/items/new") public String create(@Valid BookForm form, BindingResult result) { if (result.hasErrors()) { System.out.println(result.getFieldError()); return "items/createItemForm"; } Book book = new Book(); book.setName(form.getName()); book.setPrice(form.getPrice()); book.setStockQuantity(form.getStockQuantity()); book.setAuthor(form.getAuthor()); book.setIsbn(form.getIsbn()); itemService.saveItem(book); return "redirect:/items"; } @GetMapping("/items") public String list(Model model) { List items = itemService.findItems(); model.addAttribute("items", items); return "items/itemList"; } @GetMapping("items/{itemId}/edit") public String updateItemForm(@PathVariable("itemId") Long itemId, Model model) { Book item = (Book) itemService.findOne(itemId); BookForm form = new BookForm(); form.setName(item.getName()); form.setPrice(item.getPrice()); form.setStockQuantity(item.getStockQuantity()); form.setAuthor(item.getAuthor()); form.setIsbn(item.getIsbn()); model.addAttribute("bookForm", form); return "items/updateItemForm"; } @PostMapping("/items/{itemId}/edit") public String updateItem(@ModelAttribute("bookForm") BookForm form) { Book book = new Book(); book.setId(form.getId()); book.setName(form.getName()); book.setPrice(form.getPrice()); book.setStockQuantity(form.getStockQuantity()); book.setAuthor(form.getAuthor()); book.setIsbn(form.getIsbn()); itemService.saveItem(book); return "redirect:/items"; } } ItemServicepackage jpabook.jpashop.repository; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.*; import jpabook.jpashop.domain.Member; import lombok.RequiredArgsConstructor; import jpabook.jpashop.domain.Order; import org.springframework.data.web.config.EnableSpringDataWebSupport; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; @Repository @RequiredArgsConstructor public class OrderRepository { private final EntityManager em; public void save(Order order) { em.persist(order); } public Order findOne(Long id) { return em.find(Order.class, id); } /* JPQL */ public List findAll(OrderSearch orderSearch) { //language=JPAQL String jpql = "select o From Order o join o.member m"; boolean isFirstCondition = true; //주문 상태 검색 if (orderSearch.getOrderStatus() != null) { if (isFirstCondition) { jpql += " where"; isFirstCondition = false; } else { jpql += " and"; } jpql += " o.status = :status"; } //회원 이름 검색 if (StringUtils.hasText(orderSearch.getMemberName())) { if (isFirstCondition) { jpql += " where"; isFirstCondition = false; } else { jpql += " and"; } jpql += " m.name like :name"; } TypedQuery query = em.createQuery(jpql, Order.class) .setMaxResults(1000); //최대 1000건 if (orderSearch.getOrderStatus() != null) { query = query.setParameter("status", orderSearch.getOrderStatus()); } if (StringUtils.hasText(orderSearch.getMemberName())) { query = query.setParameter("name", orderSearch.getMemberName()); } return query.getResultList(); } /* JPA Criteria */ public List findAllByCriteria(OrderSearch orderSearch) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Order.class); Root o = cq.from(Order.class); Join m = o.join("member", JoinType.INNER); //회원과 조인 List criteria = new ArrayList(); //주문 상태 검색 if (orderSearch.getOrderStatus() != null) { Predicate status = cb.equal(o.get("status"), orderSearch.getOrderStatus()); criteria.add(status); } //회원 이름 검색 if (StringUtils.hasText(orderSearch.getMemberName())) { Predicate name = cb.like(m.get("name"), "%" + orderSearch.getMemberName() + "%"); criteria.add(name); } cq.where(cb.and(criteria.toArray(new Predicate[criteria.size()]))); TypedQuery query = em.createQuery(cq).setMaxResults(1000); //최대 1000 건 return query.getResultList(); } } ItemRepositorypackage jpabook.jpashop.repository; import jakarta.persistence.EntityManager; import jpabook.jpashop.domain.Item.Item; import lombok.RequiredArgsConstructor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository @RequiredArgsConstructor public class ItemRepository { private final EntityManager em; public void save(Item item) { if (item.getId() == null) { em.persist(item); } else { em.merge(item); } } public Item findOne(Long id) { return em.find(Item.class, id); } public List findAll() { return em.createQuery("select i from Item i", Item.class) .getResultList(); } } updateItemForm.html 상품명 가격 수량 저자 ISBN Submit
- 0
- 3
- 67
질문&답변
2024.09.23
상품 수정시 기존값이 그대로 유지되어 나타나요
Itempackage jpabook.jpashop.domain.Item; import jakarta.persistence.*; import jpabook.jpashop.domain.Category; import jpabook.jpashop.exception.NotEnoughStockException; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "dtype") @Getter @Setter 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 categories = new ArrayList(); //==비즈니스 로직==// /* * stock 증가 */ public void addStock(int quantity) { this.stockQuantity += quantity; } /* * stock 감소 */ public void removeStock(int quantity) { int restStock = this.stockQuantity - quantity; if (restStock Bookpackage jpabook.jpashop.domain.Item; import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import lombok.Getter; import lombok.Setter; @Entity @DiscriminatorValue("B") @Getter @Setter public class Book extends Item { private String author; private String isbn; } BookFormpackage jpabook.jpashop.controller; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import lombok.Getter; import lombok.Setter; @Getter @Setter public class BookForm { private Long id; @NotEmpty(message = "상품명은 필수 입니다") private String name; @NotNull(message = "가격은 필수입니다.") private Integer price; @NotNull(message = "수량은 필수입니다.") private Integer stockQuantity; private String author; private String isbn; }
- 0
- 3
- 67