Skip to content

Commit 24d69c5

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 a5f4bc0 commit 24d69c5

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
@@ -530,8 +530,12 @@ public <S extends T> long count(Example<S> example) {
530530
*/
531531
@Override
532532
public <S extends T> boolean exists(Example<S> example) {
533-
return !getQuery(new ExampleSpecification<S>(example, escapeCharacter), example.getProbeType(), Sort.unsorted())
534-
.getResultList().isEmpty();
533+
Specification<S> spec = new ExampleSpecification<>(example, this.escapeCharacter);
534+
CriteriaQuery<Integer> cq = this.em.getCriteriaBuilder().createQuery(Integer.class);
535+
cq.select(this.em.getCriteriaBuilder().literal(1));
536+
applySpecificationToCriteria(spec, example.getProbeType(), cq);
537+
TypedQuery<Integer> query = applyRepositoryMethodMetadata(this.em.createQuery(cq));
538+
return query.setMaxResults(1).getSingleResult() != null;
535539
}
536540

537541
/*

0 commit comments

Comments
 (0)