Java

Spring Batch - 데이터 생성, 즉시로딩/지연로딩

내이름효주 2024. 4. 23. 15:35
  • 테스트 데이터 생성 (DevInitData)
    • yml -> profile: active: dev (활성화)
  • 즉시로딩
    • 연관된 엔티티를 즉시 조회
    • SQL 조인을 사용해 한번에 조회
@ManyToOne(fetch = FetchType.EAGER)
  • 지연로딩 - 엔티티의 조회 시점을 실제 해당 객체가 사용될 때로 늦춤
    • 연관된 엔티티를 프록시로 조회
    • 프록시를 실제 사용할 때 초기화하면서 데이터베이스 조회
@ManyToOne(fetch = FetchType.LAZY)
  • @ManyToOne, @OneToMany, @OneToOne, @ManyToMany  엔티티간의 연관관계를 지정해주기 위한 어노테이션
    • @ManyToOne, @OneToOne 의 fetch 타입의 기본값은 FetchType.EAGER
      ➡ 즉시로딩을 사용할때 추가로 설정해줄 필요가 없음
    • @OneToMany, @ManyToMany 의 fetch 타입의 기본값은 FetchType.LAZY
      ➡ 즉시로딩을 사용할때 추가로 설정
  • 쇼핑몰 만들기
    • 동일 회원이 같은 상품을 2번 이상 장바구니에 담는 경우 수량 수정 
       public CartItem addItem(Member member, ProductOption productOption, int quantity) {
              CartItem oldCartItem = cartItemRepository.findByMemberIdAndProductOptionId(member.getId(),productOption.getId()).orElse(null);
      
              if(oldCartItem != null){
                  oldCartItem.setQuantity(oldCartItem.getQuantity()+quantity); // 기존 수량에 등록한 수량 추가
                  cartItemRepository.save(oldCartItem);
      
                  return oldCartItem;
              }
              CartItem cartItem = CartItem.builder()
                      .member(member)
                      .productOption(productOption)
                      .quantity(quantity)
                      .build();
      
              cartItemRepository.save(cartItem);
      
              return cartItem;
              
              }
      }