TIL

[Spring] JPA deleteAll

승무_ 2023. 1. 26. 19:37

repository.deleteAll() 과 repository.deleteAllInBatch()의 차이가 무엇일까?

@Override
@Transactional
public void deleteAll() {

	for (T element : findAll()) {
		delete(element);
	}
}

delete 쿼리가 하나씩 날라간다. 만약 테스트 데이터로 1000개 의 item 을 삭제해야 한다면 1000번의 delete 쿼리가 실행되는 것이다.

@Override
@Transactional
public void deleteAllInBatch(Iterable<T> entities) {

	Assert.notNull(entities, "Entities must not be null!");

	if (!entities.iterator().hasNext()) {
		return;
	}

	applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()), entities, em)
			.executeUpdate();
}


여기서 보면 getQueryString 에 매개변수로 DELETE_ALL_QUERY_STRING 을 받는다.

public abstract class QueryUtils {
	public static final String COUNT_QUERY_STRING = "select count(%s) from %s x";
	public static final String DELETE_ALL_QUERY_STRING = "delete from %s x";
	public static final String DELETE_ALL_QUERY_BY_ID_STRING = "delete from %s x where %s in :ids";
}


해당하는 상수를 타고 들어가면 QueryUtils 에 DELETE_ALL_QUERY_STRING 이라는 상수가 있고
delete from %s x 와 같이 작성된 쿼리가 있다.
즉, delete from 테이블 이름 이 되는것이다.