fix(api): clear EntityManager before deleting books (#1467)

This commit is contained in:
James Ward
2026-05-23 20:58:17 -06:00
committed by GitHub
parent db09c39192
commit f9d9000706
2 changed files with 12 additions and 3 deletions
@@ -462,13 +462,13 @@ public class BookService {
}
}
bookRepository.deleteAllInBatch(books);
// Because this is `InBatch` we need to clear and flush the entity manager to
// prevent unexpected updates of records when the transaction commits.
entityManager.flush();
entityManager.clear();
bookRepository.deleteAllInBatch(books);
auditService.log(AuditAction.BOOK_DELETED, "Deleted " + ids.size() + " book(s)");
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
@@ -21,6 +21,7 @@ import org.booklore.util.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
@@ -391,7 +392,15 @@ class BookServiceTest {
bookService.deleteBooks(Set.of(11L)).getBody();
verify(entityManager).clear();
InOrder order = inOrder(entityManager, bookRepository);
// The order of the calls is important - we MUST flush, then clear, and
// only then can we delete. If we change the order then we end up with errors.
order.verify(entityManager).flush();
order.verify(entityManager).clear();
order.verify(bookRepository).deleteAllInBatch(anyList());
order.verifyNoMoreInteractions();
}
@Test