Friday, June 1, 2012

Spring Data JPA - Limit query size

This one is very informative and short:

If you are using Spring Data JPA, you are probably familiar with the technique of query creation out of methods names.

Following that mechanism, there is no explicit way to use the LIMIT keyword in the query name,
However, there is a simple way to use the SQL LIMIT with these queries.
The implicit way to limit the query result size is to utilize the pagination mechanism.
Simply provide and extra paging object with the objects number you need to limit.

Below is a simplified example of how the repository interface should be used:
public interface EntityRepository extends CrudRepository, JpaSpecificationExecutor {

 List findByEntityMemberNameLike(String query, Pageable pageable);//Pageable will limit the query result


Below is a simplified example of how the usage of such query could be:
EntityRepository entityRepository;


int queryLimit = 10;
List queryResults = entityRepository.findByEntityMemberNameLike(queryString, new PageRequest(0, queryLimit));

No comments :

Post a Comment