Can I combine a @Query definition with a Specification in a Spring Data JPA repository method?

First thing, you should read this Spring blog post.

Second, according to the JpaSpecificationExecutor interface, that your repositories should implement, the following method take a Specification argument:

  • count(Specification<T> spec)
  • List<T> findAll(Specification<T> spec)
  • Page<T> findAll(Specification<T> spec, Pageable pageable)
  • List<T> findAll(Specification<T> spec, Sort sort)
  • T findOne(Specification<T> spec)

So, you can’t mix a @Query definition with a Specification.

However, since you can express the firstName <> ?1 condition using a Specification and because you combine as many specifications as you want, you can rewrite the whole @Query using Specification(s) only.

Leave a Comment