diff --git a/spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java b/spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java index bda460e3c5..27dc8a54ce 100644 --- a/spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java +++ b/spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java @@ -93,6 +93,7 @@ * @author Ernst-Jan van der Laan * @author Diego Krupitza * @author Seol-JY + * @author SangMin Lee */ @Repository @Transactional(readOnly = true) @@ -237,6 +238,15 @@ public void deleteAllByIdInBatch(Iterable ids) { deleteAllInBatch(entities); } else { + ids.forEach(id -> { + T entity = entityManager.find(entityInformation.getJavaType(), id); + if (entity != null) { + entityManager.remove(entity); + } + }); + + entityManager.clear(); + String queryString = String.format(DELETE_ALL_QUERY_BY_ID_STRING, entityInformation.getEntityName(), entityInformation.getIdAttribute().getName()); @@ -275,6 +285,14 @@ public void deleteAllInBatch(Iterable entities) { return; } + for (T entity : entities) { + if (entityManager.contains(entity)) { + entityManager.remove(entity); + } + } + + entityManager.clear(); + applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()), entities, entityManager) .executeUpdate(); } diff --git a/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java b/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java index 225336983e..a240e32116 100644 --- a/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java +++ b/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java @@ -97,6 +97,7 @@ * @author Geoffrey Deremetz * @author Krzysztof Krason * @author Yanming Zhou + * @author SangMin Lee */ @ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:application-context.xml") @@ -3416,6 +3417,35 @@ void mergeWithNativeStatement() { .map(User::getAge).contains(30); } + @Test // GH-3360 + void removeWhenDeleteAllInBatchWithEntities() { + + flushTestUsers(); + List userList = repository.findAll(); + + repository.deleteAllInBatch(userList); + + userList.forEach(user -> + assertThat(em.contains(user)).isFalse() + ); + + } + + @Test // GH-3360 + void removeWhenDeleteAllByIdInBatch() { + + flushTestUsers(); + List userList = repository.findAll(); + List userIds = userList.stream().map(User::getId).toList(); + + repository.deleteAllByIdInBatch(userIds); + + userList.forEach(user -> + assertThat(em.contains(user)).isFalse() + ); + + } + private Page executeSpecWithSort(Sort sort) { flushTestUsers();