스프링데이터 + JPA/API 개발

5. 조회용 샘플 데이터 입력

sdafdq 2023. 11. 12. 19:21

이렇게 두 건의 주문을 만들거임

 

@Component
@RequiredArgsConstructor
public class InitDb {

    private final InitService initService;

    @PostConstruct
    public void init(){
        initService.dbInit1();
        initService.dbInit2();
    }

    @Component
    @Transactional
    @RequiredArgsConstructor
    static class InitService{
        private final EntityManager em;
        public void dbInit1(){
            Member member = createMember("userA", "서울", "1","1111");
            em.persist(member);

            Book book1 = createBook("JPA1 BOOK",10000,100);
            em.persist(book1);

            Book book2 = createBook("JPA2 BOOK",20000,100);
            em.persist(book2);

            OrderItem orderItem1 = OrderItem.createOrderItem(book1, 10000, 1);
            OrderItem orderItem2 = OrderItem.createOrderItem(book2, 20000, 2);

            Delivery delivery = new Delivery();
            delivery.setStatus(DeliveryStatus.READY);
            delivery.setAddress(member.getAddress());
            Order order = Order.createOrder(member, delivery, orderItem1, orderItem2);

            em.persist(order);

        }

        private static Book createBook(String name, int price, int stockQuantity) {
            Book book =  new Book();
            book.setName(name);
            book.setPrice(price);
            book.setStockQuantity(stockQuantity);
            return book;
        }

        public void dbInit2(){
            Member member = createMember("userB", "진주", "2","2222");
            em.persist(member);

            Book book1 = createBook("SPRING1 BOOK",20000,200);
            em.persist(book1);

            Book book2 = createBook("SPRING2 BOOK",40000,300);
            em.persist(book2);

            OrderItem orderItem1 = OrderItem.createOrderItem(book1, 20000, 3);
            OrderItem orderItem2 = OrderItem.createOrderItem(book2, 40000, 4);

            Delivery delivery = new Delivery();
            delivery.setStatus(DeliveryStatus.READY);
            delivery.setAddress(member.getAddress());
            Order order = Order.createOrder(member, delivery, orderItem1, orderItem2);

            em.persist(order);

        }

        private static Member createMember(String name, String city, String street, String zipcode) {
            Member member = new Member();
            member.setName(name);
            member.setAddress(new Address(city, street, zipcode));
            return member;
        }
    }
}

 

이렇게 컴포넌트로 등록 후

@PostConstruct 하면 빈으로 잡힌 후, 실행 됨.

그냥 멤버~ 주문 등록하는거임.

 

참고로 저렇게 트랜잭션을 따로 빼는 이유는 스프링 생명주기상 @PostConstruct는 트랜잭션이 잘 안먹힐 수 있다고 하여  따로 빼서 확실히 트랜잭션 범위를 잡음.

 

 

'스프링데이터 + JPA > API 개발' 카테고리의 다른 글

7. 엔티티를 Dto로  (0) 2023.11.13
6. 지연로딩과 조회성능 최적화  (0) 2023.11.13
4. API 성능 최적화  (0) 2023.11.12
3. 회원 조회 API  (0) 2023.11.12
2. 회원 수정 API  (0) 2023.11.12