From bfa7be315a9ca69dcd4cbf76a539347bbec88b3f 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 | 4 +++- .../data/jpa/repository/UserRepositoryTests.java | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) 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 adfc5e76b..5f8a82715 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 @@ -80,6 +80,7 @@ import org.springframework.util.Assert; * @author Sander Krabbenborg * @author Jesse Wouters * @author Greg Turnquist + * @author Yanming Zhou */ @Repository @Transactional(readOnly = true) @@ -530,12 +531,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 c2f7c4b52..a4a438e85 100644 --- a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java @@ -2318,6 +2318,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() {