Correctly handle exists when it should return false.

In the previous implementation it would throw an exception.

Original pull request #2368
This commit is contained in:
Jens Schauder
2021-12-03 11:27:11 +01:00
parent 09e4d27d98
commit e1df922bbc
2 changed files with 18 additions and 3 deletions

View File

@@ -75,8 +75,8 @@ import org.springframework.util.Assert;
* @author Moritz Becker
* @author Sander Krabbenborg
* @author Jesse Wouters
* @param <T> the type of the entity to handle
* @param <ID> the type of the entity's identifier
* @author Greg Turnquist
* @author Yanming Zhou
*/
@Repository
@Transactional(readOnly = true)
@@ -527,12 +527,13 @@ public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T
*/
@Override
public <S extends T> boolean exists(Example<S> example) {
Specification<S> spec = new ExampleSpecification<>(example, this.escapeCharacter);
CriteriaQuery<Integer> cq = this.em.getCriteriaBuilder().createQuery(Integer.class);
cq.select(this.em.getCriteriaBuilder().literal(1));
applySpecificationToCriteria(spec, example.getProbeType(), cq);
TypedQuery<Integer> query = applyRepositoryMethodMetadata(this.em.createQuery(cq));
return query.setMaxResults(1).getSingleResult() != null;
return query.setMaxResults(1).getResultList().size() == 1;
}
/*

View File

@@ -2058,6 +2058,20 @@ public class UserRepositoryTests {
assertThat(exists).isEqualTo(true);
}
@Test // GH-2368
void existsByExampleNegative() {
flushTestUsers();
User prototype = new User();
prototype.setAge(4711); // there is none with that age
Example<User> example = Example.of(prototype, matching().withIgnorePaths("createdAt"));
boolean exists = repository.exists(example);
assertThat(exists).isEqualTo(false);
}
@Test // DATAJPA-905
void executesPagedSpecificationSettingAnOrder() {