From e1df922bbcdd7ed4eb3bc87437158bb40cddb3d6 Mon Sep 17 00:00:00 2001 From: Jens Schauder Date: Fri, 3 Dec 2021 11:27:11 +0100 Subject: [PATCH] Correctly handle exists when it should return false. In the previous implementation it would throw an exception. Original pull request #2368 --- .../repository/support/SimpleJpaRepository.java | 7 ++++--- .../data/jpa/repository/UserRepositoryTests.java | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java b/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java index 75ed0f491..231a50813 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java @@ -75,8 +75,8 @@ import org.springframework.util.Assert; * @author Moritz Becker * @author Sander Krabbenborg * @author Jesse Wouters - * @param the type of the entity to handle - * @param the type of the entity's identifier + * @author Greg Turnquist + * @author Yanming Zhou */ @Repository @Transactional(readOnly = true) @@ -527,12 +527,13 @@ public class SimpleJpaRepository implements JpaRepositoryImplementation boolean exists(Example example) { + Specification spec = new ExampleSpecification<>(example, this.escapeCharacter); CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery(Integer.class); cq.select(this.em.getCriteriaBuilder().literal(1)); applySpecificationToCriteria(spec, example.getProbeType(), cq); TypedQuery query = applyRepositoryMethodMetadata(this.em.createQuery(cq)); - return query.setMaxResults(1).getSingleResult() != null; + return query.setMaxResults(1).getResultList().size() == 1; } /* diff --git a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java index ce28bbfd3..e0173f3e0 100644 --- a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java @@ -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 example = Example.of(prototype, matching().withIgnorePaths("createdAt")); + boolean exists = repository.exists(example); + + assertThat(exists).isEqualTo(false); + } + @Test // DATAJPA-905 void executesPagedSpecificationSettingAnOrder() {