Java/JPA

[JPA] Spring Data에서 save()와 saveAll()의 성능 차이

yaini 2022. 4. 4. 23:17
반응형

https://www.baeldung.com/spring-data-save-saveall

해당 글은 위 링크를 번역한 글입니다.

 

Overview

Spring Data의 save와 saveAll의 성능 차이를 알아보자.

 

Application

Book.java

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String title;
    private String author;

    // constructors, standard getters and setters
}

BookRepository.java

public interface BookRepository extends JpaRepository<Book, Long> {
}

Spring 어플리케이션에서 해당 entity와 repository를 사용하여 테스트해본다.

 

Performance

save() method 테스트

for(int i = 0; i < bookCount; i++) {
    bookRepository.save(new Book("Book " + i, "Author " + i));
}

saveAll() method 테스트

List<Book> bookList = new ArrayList<>();
for (int i = 0; i < bookCount; i++) {
    bookList.add(new Book("Book " + i, "Author " + i));
}

bookRepository.saveAll(bookList);

save 메소드 테스트는 2초가 소요되는 것에 반해, saveAll 메소드 테스트는 약 0.3초가 소요되었다.

JPA Batch Insert 에선 save 메소드에서 약 10%의 성능 저하가, saveAll 메소드에선 60% 의 성능 향상이 관찰되었다.

 

Differences

위와 같은 성능 차이가 발생하는 이유는 @Transactional 때문이다.

디폴트로 설정된 트랜잭션 전파 타입은 REQUIRED로

  • 별도의 트랜잭션이 설정되어 있지 않다면 새로운 트랜잭션을 생성
  • 트랜잭션이 설정되어 있다면 기존의 트랜잭션 내에서 로직을 실행

하는 옵션이다.

따라서 save 메소드를 호출할 때마다, 새로운 트랜잭션이 생성되고 반면에 saveAll 메소드를 호출했을땐 하나의 트랜잭션만 생성되고 재사용된다.

이러한 오버헤드는 batch를 수행할 때 더 크게 작용된다.

반응형