Optimize SimpleJpaRepository.exists(Example) for better performance.

1. Set max results to 1 to avoid full scan
2. Select 1 to reduce size of ResultSet

Original pull request #2368
This commit is contained in:
Yanming Zhou
2021-12-01 10:47:15 +08:00
committed by Jens Schauder
parent a5f4bc0ebb
commit 24d69c5452

View File

@@ -530,8 +530,12 @@ public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T
*/
@Override
public <S extends T> boolean exists(Example<S> example) {
return !getQuery(new ExampleSpecification<S>(example, escapeCharacter), example.getProbeType(), Sort.unsorted())
.getResultList().isEmpty();
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;
}
/*