
강의의 내용 중 Community Feed 기능을 구현 하던 중 좋아요를 누른 후 취소하는 기능을 구현한 내용이 있다.

이때 Spring Data JPA의 deleteById() 를 사용했는데 그냥 delete() 를 사용하면 안되나?? 생각이 들어 한번 찾아보았다.
Sprinf Data JPA 에선 deleteById(), delete() 메소드를 이용해 DB에 delete 쿼리를 날릴 수 있음.
또한 이들은 이미 구현되어 있기 때문에 JpaRepository 를 상속받은 interface를 구현(Impl)하여 사용할 수 있음.

deleteById(ID Id);void deleteById(ID id)
Deletes the entity with the given id.
If the entity is not found in the persistence store it is silently ignored.
Parameters:id - must not be null.Throws:IllegalArgumentException - in case the given id is null
jpaLikeRepository.deleteById(likeEntity.getId());
SimpleJpaRepository<T, ID> 에 작성되어 있는 deleteById()를 살펴보자.

id 값이 null 이라면, IllegalArgumentException 에러를 던진다고 함.
내부적으로 findById를 통해 해당 엔티티를 찾은 후, delete를 이용해 삭제함.
삭제하려는 Entity가 영속 상태가 아니어도 삭제가 가능함.
JPA 1차 캐시(Persistence Context)를 무시하고 바로 DB에서 삭제
동일 트랜잭션에서 findById()로 조회 시 이미 삭제된 데이터가 캐싱될 수 있음.
객체를 미리 조회하지 않고 바로 ID만 넘길 때 적합함.
delete(T entity);void delete(T entity)
Deletes a given entity.
Parameters:entity - must not be null.
Throws:
IllegalArgumentException - in case the given entity is null.
OptimisticLockingFailureException - when the entity uses optimistic locking and has a version attribute with a different value from that found in the persistence store.
Also thrown if the entity is assumed to be present but does not exist in the database.
jpaLikeRepository.delete(likeEntity);
SimpleJpaRepository<T, ID> 에 작성되어 있는 delete()를 살펴보자.

entity 값이 null 이면, IllegalArgumentException 에러를 던진다고 함.
아직 저장되지 않은 엔티티라면 return으로 메소드를 종료함.
원본 클래스를 불러 프록시 객체가 감싸고 있는지 확인을 진행한 후,
DB에서 해당 엔티티가 존재하는지 확인하고 없다면 return, 있다면 삭제를 수행함.
이때
영속성 컨텍스트에 포함 - entityManager.remove(entity);
영속성 컨텍스트에 포함 X - entityManager.merge(entity); (병합 후 삭제)
의 과정을 거침.
1) 엔티티가 버전(Version)을 관리하고 있어, DB의 버전과 다르거나,
2) DB에 존재할 것으로 예상했으나, 없을 경우
OptimisticLockingFailureException 해당 에러를 발생시킴.
JPA 1차 캐시를 활용해 삭제 전 Entity를 관리함.
Entity가 Detached(준영속) 상태이면 예외가 발생.
findById()로 엔티티를 조회한 후 삭제해야 안전함.
| 사용 상황 | deleteById() | delete() |
|---|---|---|
| ID만 알고 있음 | 가능 | 불가(Entity 필요) |
| 이미 조회한 엔티티 삭제 | 가능 | 가능 |
| 엔티티가 준영속 상태일 때 | 가능 | 예외 발생 |
| 영속성 컨텍스트 고려 | 무시 | 반영 |