💡 개요
오늘은 Spring의 테스트에서 사용한 데이터 삭제를 위해 사용되는 deleteAll() 과 deleteAllInBatch() 의 차이에 대해 정리해보자.
📕 deleteAll()
JPA에서 deleteAll() 메서드는 말 그대로 테이블에 위치한 데이터를 모두 삭제하는 데 사용된다.
deleteAll()은 CrudRepository 인터페이스에 선언되어 있는 메서드이고, 구현은 SimpleJpaRepository에 되어 있다.
@Override
@Transactional
public void deleteAll() {
for (T element : findAll()) {
delete(element);
}
}
@Override
@Transactional
@SuppressWarnings("unchecked")
public void delete(T entity) {
Assert.notNull(entity, ENTITY_MUST_NOT_BE_NULL);
if (entityInformation.isNew(entity)) {
return;
}
if (entityManager.contains(entity)) {
entityManager.remove(entity);
return;
}
Class<?> type = ProxyUtils.getUserClass(entity);
// if the entity to be deleted doesn't exist, delete is a NOOP
T existing = (T) entityManager.find(type, entityInformation.getId(entity));
if (existing != null) {
entityManager.remove(entityManager.merge(entity));
}
}
위 코드에서 deleteAll() 메서드는 모든 엔티티를 조회한 후, delete() 메서드를 반복적으로 호출하여 삭제한다.
즉, findAll()을 통해 엔티티 조회 → 조회된 모든 엔티티를 이용해 delete() 메서드 실행의 과정으로 동작한다.
결국 엔티티의 수 만큼 데이터베이스에 접근해야 한다.
📕 deleteAllInBatch()
SimpleJpaRepository.deleteAllInBatch() 메서드 코드는 다음과 같다.
@Override
@Transactional
public void deleteAllInBatch() {
Query query = entityManager.createQuery(getDeleteAllQueryString());
applyQueryHints(query);
query.executeUpdate();
}
private String getDeleteAllQueryString() {
return getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName());
}
public abstract class QueryUtils {
...
public static final String DELETE_ALL_QUERY_STRING = "delete from %s x";
...
}
deleteAllInBatch()는 개별 엔티티를 삭제하는 방식이 아니라 JPA를 통해 한 번의 DELETE 쿼리를 생성하고 실행하는 방식으로 동작한다.
이 방식의 장점은 데이터베이스에 접근하는 횟수를 최소화할 수 있다는 점이다.
일반적으로 데이터베이스에서 CRUD 작업을 수행할 때는 3-Way Handshake 과정이 필요하며, 이 과정에서 많은 리소스와 시간이 소모된다.
deleteAllInBatch()는 한 번의 DELETE 쿼리를 실행하므로, 대량 데이터를 삭제할 때 성능이 훨씬 우수하다.
'개발 일기' 카테고리의 다른 글
[개발 일기] 2025.03.31 - WSS (WebSocket Secure) (0) | 2025.03.31 |
---|---|
[개발 일기] 2025.03.30 - Docker를 사용하는 이유가 뭐에요? (0) | 2025.03.30 |
[개발 일기] 2025.03.28 - Auto Increment Long PK vs UUID (0) | 2025.03.28 |
[개발 일기] 2025.03.27 - 커스텀 어노테이션 (0) | 2025.03.27 |
[개발 일기] 2025.03.26 - REDO, UNDO (0) | 2025.03.26 |