@@ -29,7 +29,7 @@ public void batchAuthorsAndBooks() {
2929 Author author = new Author ();
3030 author .setName ("Name_" + i );
3131 author .setGenre ("Genre_" + i );
32- author .setAge (18 + i );
32+ author .setAge (( int ) (( Math . random () + 0.1 ) * 100 ) );
3333
3434 for (int j = 0 ; j < 5 ; j ++) {
3535 Book book = new Book ();
@@ -45,39 +45,42 @@ public void batchAuthorsAndBooks() {
4545 authorRepository .saveAll (authors );
4646 }
4747
48- // explicitly delete all records from each table (ignores orphanRemoval = true)
48+ // explicitly delete all records from each table
4949 @ Transactional
5050 public void deleteAuthorsAndBooksViaDeleteAllInBatch () {
5151 authorRepository .deleteAllInBatch ();
5252 bookRepository .deleteAllInBatch ();
5353 }
5454
55- // explicitly delete all records from each table (ignores orphanRemoval = true)
55+ // explicitly delete all records from each table
5656 @ Transactional
5757 public void deleteAuthorsAndBooksViaDeleteInBatch () {
58- List <Author > authors = authorRepository .fetchAllAuthorsAndBooks ( );
58+ List <Author > authors = authorRepository .fetchAuthorsAndBooks ( 60 );
5959
6060 authorRepository .deleteInBatch (authors );
6161 authors .forEach (a -> bookRepository .deleteInBatch (a .getBooks ()));
6262 }
6363
6464 // good if you need to delete in a classical batch approach
65- // (uses orphanRemoval = true, but generates 20 batches because DELETE statements are not sorted at all)
65+ // deletes are cascaded by CascadeType.REMOVE and batched as well
66+ // the DELETE statements are not sorted at all and this causes more batches than needed for this job
6667 @ Transactional
67- public void deleteAuthorsAndBooksViaDeleteAll () {
68- authorRepository .deleteAll (); // for a collection of certain Authors use deleteAll(Iterable<? extends T> entities)
68+ public void deleteAuthorsAndBooksViaDeleteAll () {
69+ List <Author > authors = authorRepository .fetchAuthorsAndBooks (60 );
70+
71+ authorRepository .deleteAll (authors ); // for deleting all Authors use deleteAll()
6972 }
7073
7174 // good if you need to delete in a classical batch approach
72- // (uses orphanRemoval = true, and generates only 3 batches)
75+ // (uses orphanRemoval = true, and optimize the number of batches)
7376 @ Transactional
7477 public void deleteAuthorsAndBooksViaDelete () {
7578
76- List <Author > authors = authorRepository .fetchAllAuthorsAndBooks ( );
77-
79+ List <Author > authors = authorRepository .fetchAuthorsAndBooks ( 60 );
80+
7881 authors .forEach (Author ::removeBooks );
7982 authorRepository .flush ();
8083
81- authors .forEach (authorRepository ::delete ); // or, authorRepository.deleteAll();
84+ authors .forEach (authorRepository ::delete ); // or, authorRepository.deleteAll(authors );
8285 }
8386}
0 commit comments