Skip to content

DATAJPA-1818 - Implements CrudRepository.delete(Iterable<ID> ids). #435

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.5.0-SNAPSHOT</version>
<version>2.5.0-DATAJPA-1818-SNAPSHOT</version>

<name>Spring Data JPA</name>
<description>Spring Data module for JPA repositories.</description>
Expand All @@ -25,7 +25,7 @@
<hibernate>5.4.8.Final</hibernate>
<mockito>2.19.1</mockito>
<hibernate.groupId>org.hibernate</hibernate.groupId>
<springdata.commons>2.5.0-SNAPSHOT</springdata.commons>
<springdata.commons>2.4.0-DATACMNS-800-SNAPSHOT</springdata.commons>

<java-module-name>spring.data.jpa</java-module-name>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,41 @@ public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>,
<S extends T> S saveAndFlush(S entity);

/**
* Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear
* the {@link javax.persistence.EntityManager} after the call.
* Deletes the given entities in a batch which means it will create a single {@link Query}.
*
* This kind of operation leaves JPAs first level cache and the database out of sync.
* Consider flushing the `EntityManager` before calling this method.
*
* @param entities
* @deprecated Use {@link #deleteAllInBatch(Iterable)} instead.
*/
@Deprecated
default void deleteInBatch(Iterable<T> entities){deleteAllInBatch(entities);}

/**
* Deletes the given entities in a batch which means it will create a single {@link Query}.
*
* This kind of operation leaves JPAs first level cache and the database out of sync.
* Consider flushing the `EntityManager` before calling this method.
*
* @param entities
*
* @since 3.0
*/
void deleteAllInBatch(Iterable<T> entities);


/**
* Deletes the entities identified by the given ids using a single {@link Query}.
*
* This kind of operation leaves JPAs first level cache and the database out of sync.
* Consider flushing the `EntityManager` before calling this method.
*
* @param ids
*
* @since 3.0
*/
void deleteInBatch(Iterable<T> entities);
void deleteAllByIdInBatch(Iterable<ID> ids);

/**
* Deletes all entities in a batch call.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public abstract class QueryUtils {

public static final String COUNT_QUERY_STRING = "select count(%s) from %s x";
public static final String DELETE_ALL_QUERY_STRING = "delete from %s x";
public static final String DELETE_ALL_QUERY_BY_ID_STRING = "delete from %s x where %s in :ids";

// Used Regex/Unicode categories (see https://www.unicode.org/reports/tr18/#General_Category_Property):
// Z Separator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,23 @@ public void deleteAll(Iterable<? extends T> entities) {
}
}

@Override
public void deleteAllById(Iterable<? extends ID> ids) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also add a deleteAllByIdInBatch variant?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added deleteAllByIdInBatch.

It does not work with EclipseLink since their handling of IN queries seems still to be broken.

Renamed deleteInBatch to deleteAllInBatch to match the naming conventions of CrudRepository and the new method. The old variant is deprecated and delegates to the new one.


Assert.notNull(ids, "Ids must not be null!");

for (ID id : ids) {
deleteById(id);
}
}

/*
* (non-Javadoc)
* @see org.springframework.data.jpa.repository.JpaRepository#deleteInBatch(java.lang.Iterable)
*/
@Transactional
@Override
public void deleteInBatch(Iterable<T> entities) {
public void deleteAllInBatch(Iterable<T> entities) {

Assert.notNull(entities, "Entities must not be null!");

Expand All @@ -236,6 +246,24 @@ public void deleteInBatch(Iterable<T> entities) {
.executeUpdate();
}

@Override
public void deleteAllByIdInBatch(Iterable<ID> ids) {

Assert.notNull(ids, "Ids must not be null!");

if (!ids.iterator().hasNext()) {
return;
}

String queryTemplate = DELETE_ALL_QUERY_BY_ID_STRING;
String queryString = String.format(queryTemplate, entityInformation.getEntityName(), entityInformation.getIdAttribute().getName());

Query query = em.createQuery(queryString);
query.setParameter("ids", ids);

query.executeUpdate();
}

/*
* (non-Javadoc)
* @see org.springframework.data.repository.Repository#deleteAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.springframework.data.jpa.repository;

import static java.util.Arrays.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.domain.Example.*;
import static org.springframework.data.domain.ExampleMatcher.*;
Expand All @@ -24,7 +25,6 @@
import static org.springframework.data.jpa.domain.sample.UserSpecifications.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
Expand Down Expand Up @@ -151,7 +151,7 @@ void findsAllByGivenIds() {

flushTestUsers();

assertThat(repository.findAllById(Arrays.asList(firstUser.getId(), secondUser.getId()))).contains(firstUser,
assertThat(repository.findAllById(asList(firstUser.getId(), secondUser.getId()))).contains(firstUser,
secondUser);
}

Expand All @@ -166,7 +166,7 @@ void testReadByIdReturnsNullForNotFoundEntities() {
@Test
void savesCollectionCorrectly() throws Exception {

assertThat(repository.saveAll(Arrays.asList(firstUser, secondUser, thirdUser))).hasSize(3).contains(firstUser,
assertThat(repository.saveAll(asList(firstUser, secondUser, thirdUser))).hasSize(3).contains(firstUser,
secondUser, thirdUser);
}

Expand Down Expand Up @@ -238,27 +238,41 @@ void returnsAllIgnoreCaseSortedCorrectly() throws Exception {
}

@Test
void deleteColletionOfEntities() {
void deleteCollectionOfEntities() {

flushTestUsers();

long before = repository.count();

repository.deleteAll(Arrays.asList(firstUser, secondUser));
repository.deleteAll(asList(firstUser, secondUser));

assertThat(repository.existsById(firstUser.getId())).isFalse();
assertThat(repository.existsById(secondUser.getId())).isFalse();
assertThat(repository.count()).isEqualTo(before - 2);
}

@Test
void batchDeleteColletionOfEntities() {
void batchDeleteCollectionOfEntities() {

flushTestUsers();

long before = repository.count();

repository.deleteInBatch(Arrays.asList(firstUser, secondUser));
repository.deleteAllInBatch(asList(firstUser, secondUser));

assertThat(repository.existsById(firstUser.getId())).isFalse();
assertThat(repository.existsById(secondUser.getId())).isFalse();
assertThat(repository.count()).isEqualTo(before - 2);
}

@Test // DATAJPA-1818
void deleteCollectionOfEntitiesById() {

flushTestUsers();

long before = repository.count();

repository.deleteAllById(asList(firstUser.getId(), secondUser.getId()));

assertThat(repository.existsById(firstUser.getId())).isFalse();
assertThat(repository.existsById(secondUser.getId())).isFalse();
Expand Down Expand Up @@ -603,7 +617,7 @@ void executesQueryMethodWithDeepTraversalCorrectly() throws Exception {

firstUser.setManager(secondUser);
thirdUser.setManager(firstUser);
repository.saveAll(Arrays.asList(firstUser, thirdUser));
repository.saveAll(asList(firstUser, thirdUser));

assertThat(repository.findByManagerLastname("Arrasz")).containsOnly(firstUser);
assertThat(repository.findByManagerLastname("Gierke")).containsOnly(thirdUser);
Expand All @@ -616,7 +630,7 @@ void executesFindByColleaguesLastnameCorrectly() throws Exception {

firstUser.addColleague(secondUser);
thirdUser.addColleague(firstUser);
repository.saveAll(Arrays.asList(firstUser, thirdUser));
repository.saveAll(asList(firstUser, thirdUser));

assertThat(repository.findByColleaguesLastname(secondUser.getLastname())).containsOnly(firstUser);

Expand Down Expand Up @@ -1178,7 +1192,7 @@ void findByElementCollectionAttribute() {

flushTestUsers();

List<User> result = repository.findByAttributesIn(new HashSet<>(Arrays.asList("cool", "hip")));
List<User> result = repository.findByAttributesIn(new HashSet<>(asList("cool", "hip")));

assertThat(result).containsOnly(firstUser, secondUser);
}
Expand Down Expand Up @@ -1731,7 +1745,7 @@ void findAllByExampleWithAssociation() {

firstUser.setManager(secondUser);
thirdUser.setManager(firstUser);
repository.saveAll(Arrays.asList(firstUser, thirdUser));
repository.saveAll(asList(firstUser, thirdUser));

User manager = new User();
manager.setLastname("Arrasz");
Expand Down Expand Up @@ -1854,7 +1868,7 @@ void findAllByExampleWithIncludeNull() {
fifthUser.setFirstname(firstUser.getFirstname());
fifthUser.setLastname(firstUser.getLastname());

repository.saveAll(Arrays.asList(firstUser, fifthUser));
repository.saveAll(asList(firstUser, fifthUser));

User prototype = new User();
prototype.setFirstname(firstUser.getFirstname());
Expand Down Expand Up @@ -2242,7 +2256,7 @@ void findByElementCollectionInAttributeIgnoreCase() {

flushTestUsers();

List<User> result = repository.findByAttributesIgnoreCaseIn(new HashSet<>(Arrays.asList("cOOl", "hIP")));
List<User> result = repository.findByAttributesIgnoreCaseIn(new HashSet<>(asList("cOOl", "hIP")));

assertThat(result).containsOnly(firstUser, secondUser);
}
Expand All @@ -2256,7 +2270,7 @@ void findByElementCollectionNotInAttributeIgnoreCase() {

flushTestUsers();

List<User> result = repository.findByAttributesIgnoreCaseNotIn(Arrays.asList("CooL", "HIp"));
List<User> result = repository.findByAttributesIgnoreCaseNotIn(asList("CooL", "HIp"));

assertThat(result).containsOnly(thirdUser);
}
Expand Down Expand Up @@ -2284,7 +2298,7 @@ void findByElementCollectionInAttributeIgnoreCaseWithNulls() {

flushTestUsers();

List<User> result = repository.findByAttributesIgnoreCaseIn(Arrays.asList("cOOl", null));
List<User> result = repository.findByAttributesIgnoreCaseIn(asList("cOOl", null));

assertThat(result).containsOnly(firstUser);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;

import org.junit.jupiter.api.Disabled;
import org.springframework.test.context.ContextConfiguration;

/**
Expand All @@ -25,4 +26,11 @@
@ContextConfiguration("classpath:eclipselink.xml")
class EclipseLinkJpaRepositoryTests extends JpaRepositoryTests {

@Override
/**
* Ignored until https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 is resolved.
*/
void deleteAllByIdInBatch() {
super.deleteAllByIdInBatch();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,24 @@ void executesExistsForEntityWithIdClass() {
assertThat(idClassRepository.existsById(id)).isTrue();
}

private static interface SampleEntityRepository extends JpaRepository<SampleEntity, SampleEntityPK> {
@Test // DATAJPA-1818
void deleteAllByIdInBatch() {

SampleEntity one = new SampleEntity("one", "eins");
SampleEntity two = new SampleEntity("two", "zwei");
SampleEntity three = new SampleEntity("three", "drei");
repository.saveAll(Arrays.asList(one, two, three));
repository.flush();

repository.deleteAllByIdInBatch(Arrays.asList(new SampleEntityPK("one", "eins"),new SampleEntityPK("three", "drei")));
assertThat(repository.findAll()).containsExactly(two);
}

private interface SampleEntityRepository extends JpaRepository<SampleEntity, SampleEntityPK> {

}

private static interface SampleWithIdClassRepository
private interface SampleWithIdClassRepository
extends CrudRepository<PersistableWithIdClass, PersistableWithIdClassPK> {

}
Expand Down