인프런 커뮤니티 질문&답변

양희수님의 프로필 이미지

작성한 질문수

자바 ORM 표준 JPA 프로그래밍 - 기본편

JPA Transaction에서 Delete 되지 않는 현상 관련

24.06.28 23:25 작성

·

125

0

@Entity
@Getter @Setter
@Table(name = "user")
@NoArgsConstructor
public class User extends TimeStamp {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false, unique = true)
    private String phone;

    @Column(nullable = false)
    private String address;

    @Column(nullable = false, length = 36)
    private String emailVerificationToken;

    @Column(nullable = false)
    private LocalDateTime emailVerificationExpiresAt = LocalDateTime.now().plusHours(24);

    @Column(nullable = false)
    private Boolean emailVerifiedStatus = false;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<WishList> wishes;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Cart> carts;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderList> orderList;

    public User(
        String name,
        String email,
        String password,
        String phone,
        String address,
        String emailVerificationToken,
        Boolean emailVerifiedStatus
    )
    {
        this.name = name;
        this.email = email;
        this.password = password;
        this.phone = phone;
        this.address = address;
        this.emailVerificationToken = emailVerificationToken;
        this.emailVerifiedStatus = emailVerifiedStatus;
    }
}
@Service
@RequiredArgsConstructor
public class CartService {

    private final UserRepository userRepository;
    private final ProductRepository productRepository;
    private final CartRepository cartRepository;

    public List<CartResponseDto> getCartList(Long userId) {
        User user = findByuser(userId);
        List<Cart> cartLists = user.getCarts();

        return cartLists.stream()
                .map(cartList -> new CartResponseDto(
                        cartList.getProduct().getId(),
                        cartList.getProduct().getName(),
                        cartList.getQuantity(),
                        cartList.getProduct().getPrice() * cartList.getQuantity(),
                        cartList.getProduct().getProductStock().getStockQuantity())
                ).toList();

    }
    
    // 장바구니 삭제
    @Transactional
    public List<CartResponseDto> cartDelete(Long userId, CartRequestDto cartRequestDto) {
        cartRepository.deleteByUserIdAndProductId(userId, cartRequestDto.getProductId());

        return getCartList(userId);
    }

    private User findByuser(Long userId) {
        return userRepository.findById(userId).get();
    }
}
@Repository
public interface CartRepository extends JpaRepository<Cart, Long> {

    void deleteByUserIdAndProductId(Long userId, Long productId);
}

User Entity에 cart 테이블 연관관계를 맺고
orderService에서 cartRepository.deleteByUserIdAndProductId에서 데이터를 삭제 후 getCartList
를 조회해 retrun 하려고 합니다.

예) cart table
id user_id product_id quantity
1 41 6 1

2 41 7 1

3 41 11 1

이때 cartRepository.deleteByUserIdAndProductId에서 product_id 6번을 삭제하고 getCartList를 조회하였는데 6번에 삭제되지 않고 6,7,11이 전부 조회 되었습니다.

삭제되지 않는 이유가 무었일까요 ?

Hibernate: select u1_0.id,u1_0.address,u1_0.created_at,u1_0.email,u1_0.email_verification_expires_at,u1_0.email_verification_token,u1_0.email_verified_status,u1_0.name,u1_0.password,u1_0.phone,u1_0.updated_at from user u1_0 where u1_0.email=?

Hibernate: select c1_0.id,c1_0.product_id,c1_0.quantity,c1_0.user_id from cart c1_0 where c1_0.user_id=? and c1_0.product_id=?

Hibernate: select p1_0.id,p1_0.best_status,p1_0.created_at,p1_0.description,p1_0.description_image,p1_0.name,p1_0.new_status,p1_0.price,p1_0.sold_out_status,p1_0.thumbnail_image,p1_0.updated_at from product p1_0 where p1_0.id=?

Hibernate: select ps1_0.id,p1_0.id,p1_0.best_status,p1_0.created_at,p1_0.description,p1_0.description_image,p1_0.name,p1_0.new_status,p1_0.price,p1_0.sold_out_status,p1_0.thumbnail_image,p1_0.updated_at,ps1_0.stock_quantity from product_stock_quantity ps1_0 left join product p1_0 on p1_0.id=ps1_0.product_id where ps1_0.product_id=?

Hibernate: select u1_0.id,u1_0.address,u1_0.created_at,u1_0.email,u1_0.email_verification_expires_at,u1_0.email_verification_token,u1_0.email_verified_status,u1_0.name,u1_0.password,u1_0.phone,u1_0.updated_at from user u1_0 where u1_0.id=?

Hibernate: select c1_0.user_id,c1_0.id,c1_0.product_id,p1_0.id,p1_0.best_status,p1_0.created_at,p1_0.description,p1_0.description_image,p1_0.name,p1_0.new_status,p1_0.price,p1_0.sold_out_status,p1_0.thumbnail_image,p1_0.updated_at,c1_0.quantity from cart c1_0 left join product p1_0 on p1_0.id=c1_0.product_id where c1_0.user_id=?

Hibernate: select ps1_0.id,p1_0.id,p1_0.best_status,p1_0.created_at,p1_0.description,p1_0.description_image,p1_0.name,p1_0.new_status,p1_0.price,p1_0.sold_out_status,p1_0.thumbnail_image,p1_0.updated_at,ps1_0.stock_quantity from product_stock_quantity ps1_0 left join product p1_0 on p1_0.id=ps1_0.product_id where ps1_0.product_id=?

Hibernate: select ps1_0.id,p1_0.id,p1_0.best_status,p1_0.created_at,p1_0.description,p1_0.description_image,p1_0.name,p1_0.new_status,p1_0.price,p1_0.sold_out_status,p1_0.thumbnail_image,p1_0.updated_at,ps1_0.stock_quantity from product_stock_quantity ps1_0 left join product p1_0 on p1_0.id=ps1_0.product_id where ps1_0.product_id=?

답변 1

0

김영한님의 프로필 이미지
김영한
지식공유자

2024. 06. 29. 20:50

안녕하세요. 양희수님

도움을 드리고 싶지만 질문 내용만으로는 답변을 드리기 어렵습니다.

실제 동작하는 전체 프로젝트를 ZIP파일로 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

 

주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요

 

추가로 다음 내용도 코멘트 부탁드립니다.

1. 문제 영역을 실행할 수 있는 방법

2. 문제가 어떻게 나타나는지에 대한 상세한 설명

 

링크: 공식 서포터즈

링크: 자주하는 질문

감사합니다.