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 910f02d1ad
commit bfa7be315a
2 changed files with 17 additions and 1 deletions

View File

@@ -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<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

@@ -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<User> example = Example.of(prototype, matching().withIgnorePaths("createdAt"));
boolean exists = repository.exists(example);
assertThat(exists).isEqualTo(false);
}
@Test // DATAJPA-905
void executesPagedSpecificationSettingAnOrder() {