Skip to content

Commit 6d84fb2

Browse files
committed
Correctly handle exists when it should return false.
In the previous implementation it would throw an exception. Original pull request #2368
1 parent 24d69c5 commit 6d84fb2

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
* @author Sander Krabbenborg
8181
* @author Jesse Wouters
8282
* @author Greg Turnquist
83+
* @author Yanming Zhou
8384
*/
8485
@Repository
8586
@Transactional(readOnly = true)
@@ -530,12 +531,13 @@ public <S extends T> long count(Example<S> example) {
530531
*/
531532
@Override
532533
public <S extends T> boolean exists(Example<S> example) {
534+
533535
Specification<S> spec = new ExampleSpecification<>(example, this.escapeCharacter);
534536
CriteriaQuery<Integer> cq = this.em.getCriteriaBuilder().createQuery(Integer.class);
535537
cq.select(this.em.getCriteriaBuilder().literal(1));
536538
applySpecificationToCriteria(spec, example.getProbeType(), cq);
537539
TypedQuery<Integer> query = applyRepositoryMethodMetadata(this.em.createQuery(cq));
538-
return query.setMaxResults(1).getSingleResult() != null;
540+
return query.setMaxResults(1).getResultList().size() == 1;
539541
}
540542

541543
/*

src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2318,6 +2318,20 @@ void existsByExampleWithExcludedAttributes() {
23182318
assertThat(exists).isEqualTo(true);
23192319
}
23202320

2321+
@Test // GH-2368
2322+
void existsByExampleNegative() {
2323+
2324+
flushTestUsers();
2325+
2326+
User prototype = new User();
2327+
prototype.setAge(4711); // there is none with that age
2328+
2329+
Example<User> example = Example.of(prototype, matching().withIgnorePaths("createdAt"));
2330+
boolean exists = repository.exists(example);
2331+
2332+
assertThat(exists).isEqualTo(false);
2333+
}
2334+
23212335
@Test // DATAJPA-905
23222336
void executesPagedSpecificationSettingAnOrder() {
23232337

0 commit comments

Comments
 (0)