@@ -29,7 +29,7 @@ public void batchAuthorsAndBooks() {
29
29
Author author = new Author ();
30
30
author .setName ("Name_" + i );
31
31
author .setGenre ("Genre_" + i );
32
- author .setAge (18 + i );
32
+ author .setAge (( int ) (( Math . random () + 0.1 ) * 100 ) );
33
33
34
34
for (int j = 0 ; j < 5 ; j ++) {
35
35
Book book = new Book ();
@@ -45,39 +45,42 @@ public void batchAuthorsAndBooks() {
45
45
authorRepository .saveAll (authors );
46
46
}
47
47
48
- // explicitly delete all records from each table (ignores orphanRemoval = true)
48
+ // explicitly delete all records from each table
49
49
@ Transactional
50
50
public void deleteAuthorsAndBooksViaDeleteAllInBatch () {
51
51
authorRepository .deleteAllInBatch ();
52
52
bookRepository .deleteAllInBatch ();
53
53
}
54
54
55
- // explicitly delete all records from each table (ignores orphanRemoval = true)
55
+ // explicitly delete all records from each table
56
56
@ Transactional
57
57
public void deleteAuthorsAndBooksViaDeleteInBatch () {
58
- List <Author > authors = authorRepository .fetchAllAuthorsAndBooks ( );
58
+ List <Author > authors = authorRepository .fetchAuthorsAndBooks ( 60 );
59
59
60
60
authorRepository .deleteInBatch (authors );
61
61
authors .forEach (a -> bookRepository .deleteInBatch (a .getBooks ()));
62
62
}
63
63
64
64
// 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
66
67
@ 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()
69
72
}
70
73
71
74
// 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)
73
76
@ Transactional
74
77
public void deleteAuthorsAndBooksViaDelete () {
75
78
76
- List <Author > authors = authorRepository .fetchAllAuthorsAndBooks ( );
77
-
79
+ List <Author > authors = authorRepository .fetchAuthorsAndBooks ( 60 );
80
+
78
81
authors .forEach (Author ::removeBooks );
79
82
authorRepository .flush ();
80
83
81
- authors .forEach (authorRepository ::delete ); // or, authorRepository.deleteAll();
84
+ authors .forEach (authorRepository ::delete ); // or, authorRepository.deleteAll(authors );
82
85
}
83
86
}
0 commit comments