Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data jpa @query and pageable

I'm using Spring Data JPA, and when I use @Query to to define a query WITHOUT Pageable, it works:

public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> {     @Query(value = "select * from internal_uddi where urn like %?1% or contact like %?1%",             nativeQuery = true)     List<UrnMapping> fullTextSearch(String text); } 

But if I add the second param Pageable, the @Query will NOT work, and Spring will parse the method's name, then throw the exception No property full found. Is this a bug?

public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> {     @Query(value = "select * from internal_uddi where urn like %?1% or contact like %?1%",            nativeQuery = true)     Page<UrnMapping> fullTextSearch(String text, Pageable pageable); } 
like image 511
Awakening Avatar asked Mar 12 '14 07:03

Awakening


People also ask

What is difference between CrudRepository and JpaRepository interfaces in Spring data JPA?

Crud Repository is the base interface and it acts as a marker interface. JPA also provides some extra methods related to JPA such as delete records in batch and flushing data directly to a database. It provides only CRUD functions like findOne, saves, etc. JPA repository also extends the PagingAndSorting repository.

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.

How can I apply pagination in JPA?

The simplest way to implement pagination is to use the Java Query Language – create a query and configure it via setMaxResults and setFirstResult: Query query = entityManager. createQuery("From Foo"); int pageNumber = 1; int pageSize = 10; query.

What is true about CrudRepository and JpaRepository in Spring data JPA?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

You can use pagination with a native query. It is documented here: Spring Data JPA - Reference Documentation

"You can however use native queries for pagination by specifying the count query yourself: Example 59. Declare native count queries for pagination at the query method using @Query"

public interface UserRepository extends JpaRepository<User, Long> {    @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",     countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",     nativeQuery = true)   Page<User> findByLastname(String lastname, Pageable pageable); } 
like image 72
RemusS Avatar answered Oct 09 '22 13:10

RemusS