[BAEL-4637] Performance difference between save() and saveAll() in Spring Data (#10177)

* [BAEL-4637] Performance difference between save() and saveAll() in Spring Data

* Apply suggestions from code review

* Rename IBookRepository.java to BookRepository.java
This commit is contained in:
Cicio Flaviu 2020-11-19 16:48:03 +02:00 committed by GitHub
parent f2aabf4de1
commit a198814d31
3 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package com.baeldung.spring.data.persistence.saveperformance;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String author;
public Book(final String title, final String author) {
this.title = title;
this.author = author;
}
public Book() {
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.spring.data.persistence.saveperformance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class BookApplication {
@Autowired
private BookRepository bookRepository;
public static void main(String[] args) {
SpringApplication.run(BookApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void executePerformanceBenchmark() {
int bookCount = 10000;
long start = System.currentTimeMillis();
for(int i = 0; i < bookCount; i++) {
bookRepository.save(new Book("Book " + i, "Author " + i));
}
long end = System.currentTimeMillis();
bookRepository.deleteAll();
System.out.println("It took " + (end - start) + "ms to execute save() for " + bookCount + " books");
List<Book> bookList = new ArrayList<>();
for (int i = 0; i < bookCount; i++) {
bookList.add(new Book("Book " + i, "Author " + i));
}
start = System.currentTimeMillis();
bookRepository.saveAll(bookList);
end = System.currentTimeMillis();
System.out.println("It took " + (end - start) + "ms to execute saveAll() with " + bookCount + " books\n");
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.spring.data.persistence.saveperformance;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}