본문 바로가기

Vue/bookStore

8. 도서 위시리스트 (Spring boot)

Wishlist Table 

  bid와 mid를 외래키로 받는 비식별 관계 테이블을 생성했다

  Springboot Jpa Entity에서도 복합키 설정을 해주려 했지만 many to one (lazy) 관계에서 join n+1 문제

  fetch join시 on을 사용하지 못하는 불편함과 제일 큰 문제점인 insert에 문제가 생겼다.

  필요한 데이터가 많지 않아서 Jpa에서 단일 테이블로 필요 데이터를 집어넣는 방식으로 구성을 했다.

 

 


 

@Slf4j
@Service
@RequiredArgsConstructor
public class WishlistService {

   final WishlistRepository wishlistRepository;
   final MemberRepository memberRepository;
   final BookRepository bookRepository;

    public long getMemberId(){
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        return memberRepository.getMemberIdByEmail(email);
    }

    public List<Wishlist> getWishList() {
        log.debug("my Wish List");
        log.debug("my id : " +getMemberId() );
        return wishlistRepository.findWishlistByMid(getMemberId());
    }



    public Wishlist saveWishList(WishListDTO wishListDTO) {
        long newWishIdValue = this.getnewWishIdValue(wishlistRepository);
        Book data = getWishBookData(bookRepository, wishListDTO.getBid());

        Wishlist postData = Wishlist.builder()
                .wid(newWishIdValue)
                .mid(getMemberId())
                .wishlistTitle(wishListDTO.getWishlistTitle())
                .bid(wishListDTO.getBid())
                .bookTitle(data.getBookTitle())
                .bookAuthor(data.getBookAuthor())
                .bookSalePrice(data.getBookSalePrice())
                .bookThumb(data.getBookThumb())
                .build();
        wishlistRepository.save(postData);
        return postData;

    }

    private Book getWishBookData(BookRepository bookRepository, long bid) {
        return bookRepository.getWishBook(bid);
    }

    private long getnewWishIdValue(WishlistRepository wishlistRepository) {
        long result;
        Wishlist wishOfMaxId = wishlistRepository.findTopByOrderByWidDesc();
        if (wishOfMaxId == null) {
            result = 1;
            log.debug("no board data, maxId is 1");
        } else {
            result = wishOfMaxId.getWid() + 1;
            log.debug("maxIdFromBoard=" + wishOfMaxId.getWid());
        }
        log.debug("newBoardIdValue=" + result);
        return result;
    }

    public ApiResponse<Wishlist> deleteWishList(int wid) {
        Optional<Wishlist> wishData = wishlistRepository.findWishlistByWid(wid);
        Wishlist data = wishData.orElseThrow(() -> new RuntimeException("no data"));

        boolean matchInfo= this.matchInfo(wishlistRepository, data.getMid());
        if(!matchInfo){
            return new ApiResponse<>(false, "failed to delete board id " + wid);
        }else{
            wishlistRepository.deleteWishlistByWid(wid);
            return new ApiResponse<>(true,"wid " + wid +" is successfully deleted");
        }
    }

    private boolean matchInfo(WishlistRepository wishlistRepository, long targetMid){
        long loginMid = getMemberId();
        if(loginMid!=targetMid){
            log.debug("게시글의 Id와 사용자의 ID가 일치하지 않습니다");
            return false;
        }
        return true;
    }
}

 

 

위시리스트 출력

SecurityContextHolder 를 통하여 현재 로그인 되어있는 member Id를 가져와 위시리스트 목록을 출력한다.

 

 

책 등록

Springboot controller로 들어오는 데이터는 선택한 책의 bid와 저장하고자 하는 위시리스트 이름인 wishListTitle

SecurityContextHolder 를 통하여 현재 토큰으로 로그인 되어있는 member Id를 가져오고 

controller로 들어온 bid를 사용하여 필요한 책 정보를 가져온다.

 

 

위시리스트 삭제

해당 wid로 검색한 정보가 있으면 ->

위와같은 방법으로 로그인 되어있는 member Id를 가져와서 wid에 저장된 member id와 비교한다 (matchInfo)

매치가 성공하면 삭제쿼리를 수행한다.

 

 

'Vue > bookStore' 카테고리의 다른 글

10 . 검색과 자동완성  (0) 2022.04.29
9. 도서 위시리스트  (0) 2022.03.30
7. 도서 리스트 1  (0) 2022.03.14
6. postBook - 도서등록 2  (0) 2022.02.25
5. bookStore 도서 등록  (0) 2022.02.19