Spring Data Jpa에서는 기본적인 save, delete, findById 등 다양한 메서드를 지원해준다.
그리고 오늘 원래 편하게 사용하던 delete를 사용하던 중 삭제가 안된다..?
그래서 show-sql을 사용해서 쿼리 보내는 걸 보는 중 .. delete가 안나간다..?? 뭐야!!!
원래 썼던 코드는 이렇다.
delete 메서드는 파라미터로 엔티티가 들어간다! 그래서 MyCard myCard여서 아래와 같이 했었다.
cardRepository.delete(myCard);
근데 쿼리 날라가는게 이상하다..
Hibernate:
select
member0_.member_id as member_i1_0_0_,
member0_.create_time as create_t2_0_0_,
member0_.update_time as update_t3_0_0_,
member0_.email as email4_0_0_,
member0_.firebase_token as firebase5_0_0_,
member0_.nickname as nickname6_0_0_,
member0_.password as password7_0_0_,
member0_.profile_url as profile_8_0_0_,
member0_.role as role9_0_0_
from
member member0_
where
member0_.member_id=?
Hibernate:
select
mycardlist0_.member_member_id as member_m3_1_0_,
mycardlist0_.card_id as card_id1_1_0_,
mycardlist0_.card_id as card_id1_1_1_,
mycardlist0_.card_type as card_typ2_1_1_,
mycardlist0_.member_member_id as member_m3_1_1_
from
my_card mycardlist0_
where
mycardlist0_.member_member_id=?
2023-09-23 09:37:13.542 INFO 34927 --- [nio-8080-exec-5] a.s.domain.card.service.CardService : mycardId=3
2023-09-23 09:37:13.545 INFO 34927 --- [nio-8080-exec-5] a.s.domain.card.service.CardService : mycardId=4
를 했는데 안먹는다.. 어쩌면 좋지..?
그냥 쿼리 짜서 넘겨야겠다!
@Modifying
@Query("delete from MyCard m where m.id = :id")
void delete(@Param("id") Long id);
쿼리를 짜서 작성한 코드
public void deleteMyCard(Long id, DeleteCardRequest request){
Member member = memberRepository.findById(id).orElseThrow(()
-> new BadRequestException(ErrorCode.NOT_EXISTS_USER_ID));
List<MyCard> myCardList = member.getMyCardList();
Set<String> cardTypes = new HashSet<>(request.getMyCard());
myCardList.stream()
.filter(myCard -> cardTypes.contains(myCard.getCardType()))
.forEach(myCard -> {
log.info("mycardId={}", myCard.getId());
cardRepository.delete(myCard.getId());
});
}
그랬더니 ㅠㅠ 드디어 delete 쿼리가 날라간다.
Hibernate:
select
member0_.member_id as member_i1_0_0_,
member0_.create_time as create_t2_0_0_,
member0_.update_time as update_t3_0_0_,
member0_.email as email4_0_0_,
member0_.firebase_token as firebase5_0_0_,
member0_.nickname as nickname6_0_0_,
member0_.password as password7_0_0_,
member0_.profile_url as profile_8_0_0_,
member0_.role as role9_0_0_
from
member member0_
where
member0_.member_id=?
Hibernate:
select
mycardlist0_.member_member_id as member_m3_1_0_,
mycardlist0_.card_id as card_id1_1_0_,
mycardlist0_.card_id as card_id1_1_1_,
mycardlist0_.card_type as card_typ2_1_1_,
mycardlist0_.member_member_id as member_m3_1_1_
from
my_card mycardlist0_
where
mycardlist0_.member_member_id=?
2023-09-23 09:32:41.772 INFO 34161 --- [nio-8080-exec-5] a.s.domain.card.service.CardService : mycardId=3
Hibernate:
delete
from
my_card
where
card_id=?
2023-09-23 09:32:41.784 INFO 34161 --- [nio-8080-exec-5] a.s.domain.card.service.CardService : mycardId=4
Hibernate:
delete
from
my_card
where
card_id=?
휴..!