Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to use both @Query annotation and specification in one repository method? For example I'd like to have a method like this:

@Query(value="SELECT e from EMPLOYEE where firstName <> ?1") public Page<Employee> findEmployeeBySomethigFancy(String firstName, Pageable pageable, Specification<Employee> emp); 

Is it possible or should I build the whole query as a Predicate and remove the @Query annotation?

like image 795
woytech Avatar asked Oct 15 '14 09:10

woytech


People also ask

Is it possible to define a sort type in @query annotation using Spring JPA?

Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.

How can I join JPA specification?

Joining Tables with JPA Specifications select author0_.id as id1_1_, author0_. first_name as first_na2_1_, author0_. last_name as last_nam3_1_ from author author0_ inner join author_books books1_ on author0_.id = books1_. author_id inner join book book2_ on books1_.

Is Spring data JPA an implementation of the JPA specification?

Spring Data JPA is not an implementation or JPA provider, it's just an abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

What is the use of @query in JPA?

Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.


1 Answers

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.

like image 133
Vlad Mihalcea Avatar answered Oct 15 '22 01:10

Vlad Mihalcea