Skip to content

Commit e1df922

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 09e4d27 commit e1df922

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,8 @@
7575
* @author Moritz Becker
7676
* @author Sander Krabbenborg
7777
* @author Jesse Wouters
78-
* @param <T> the type of the entity to handle
79-
* @param <ID> the type of the entity's identifier
78+
* @author Greg Turnquist
79+
* @author Yanming Zhou
8080
*/
8181
@Repository
8282
@Transactional(readOnly = true)
@@ -527,12 +527,13 @@ public <S extends T> long count(Example<S> example) {
527527
*/
528528
@Override
529529
public <S extends T> boolean exists(Example<S> example) {
530+
530531
Specification<S> spec = new ExampleSpecification<>(example, this.escapeCharacter);
531532
CriteriaQuery<Integer> cq = this.em.getCriteriaBuilder().createQuery(Integer.class);
532533
cq.select(this.em.getCriteriaBuilder().literal(1));
533534
applySpecificationToCriteria(spec, example.getProbeType(), cq);
534535
TypedQuery<Integer> query = applyRepositoryMethodMetadata(this.em.createQuery(cq));
535-
return query.setMaxResults(1).getSingleResult() != null;
536+
return query.setMaxResults(1).getResultList().size() == 1;
536537
}
537538

538539
/*

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2058,6 +2058,20 @@ void existsByExampleWithExcludedAttributes() {
20582058
assertThat(exists).isEqualTo(true);
20592059
}
20602060

2061+
@Test // GH-2368
2062+
void existsByExampleNegative() {
2063+
2064+
flushTestUsers();
2065+
2066+
User prototype = new User();
2067+
prototype.setAge(4711); // there is none with that age
2068+
2069+
Example<User> example = Example.of(prototype, matching().withIgnorePaths("createdAt"));
2070+
boolean exists = repository.exists(example);
2071+
2072+
assertThat(exists).isEqualTo(false);
2073+
}
2074+
20612075
@Test // DATAJPA-905
20622076
void executesPagedSpecificationSettingAnOrder() {
20632077

0 commit comments

Comments
 (0)