Skip to content

Commit 09e4d27

Browse files
quaffschauder
authored andcommitted
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
1 parent 721e164 commit 09e4d27

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,12 @@ public <S extends T> long count(Example<S> example) {
527527
*/
528528
@Override
529529
public <S extends T> boolean exists(Example<S> example) {
530-
return !getQuery(new ExampleSpecification<S>(example, escapeCharacter), example.getProbeType(), Sort.unsorted())
531-
.getResultList().isEmpty();
530+
Specification<S> spec = new ExampleSpecification<>(example, this.escapeCharacter);
531+
CriteriaQuery<Integer> cq = this.em.getCriteriaBuilder().createQuery(Integer.class);
532+
cq.select(this.em.getCriteriaBuilder().literal(1));
533+
applySpecificationToCriteria(spec, example.getProbeType(), cq);
534+
TypedQuery<Integer> query = applyRepositoryMethodMetadata(this.em.createQuery(cq));
535+
return query.setMaxResults(1).getSingleResult() != null;
532536
}
533537

534538
/*

0 commit comments

Comments
 (0)