I have a repository interface with some abstract methods where I use the @Query annotation. Now I would like to add limit and offset support to this queries.
example:
public interface ProductRepository
extends CrudRepository<Product, Long> {
@Query("from Product")
List<Product> findAllProducts();
}
something like this would be nice
public interface ProductRepository
extends CrudRepository<Product, Long> {
@Query("from Product limit :limit ")
List<Product> findAllProducts(@Param("limit") Integer limit);
}
But this doesn't work. There is a solution that I create an implementation of the interface (http://stackoverflow.com/questions/3479128/jpql-limit-number-of-results) But I wonder if there is not a possibility of adding offset and limit to the query or if there is an annotation for this.
+1 to what user "his" said in the comment:
"the standard way to solve the fundamental problem is to use PagingAndSortingRepository"
Here's an example. I'm throwing in sorting just as an added bonus:
public interface ArtifactRepo extends JpaRepository<Artifact, Long> {
Page<Artifact> findByComponentKey(String componentKey, Pageable pageable);
}
(You can use @Query above if you like, but JPQL doesn't itself support limits, as "his" noted.)
Then when calling it, use
PageRequest pageRequest =
new PageRequest(0, 1, Sort.Direction.DESC, "buildNumber");
Page<Artifact> artifactsPage =
artifactRepo.findByComponentKey(componentKey, pageRequest);
You can also check out this blogpost I wrote:
http://springinpractice.com/blog/categories/chapter-02-data/
limit
is not supported by JPQL. Even without it your queries are not valid JPQL queries (but may be valid HQL - and may work if your JPA provider is tolerant).
A (partial) implementation is needed so you can use the Query
interface or the criteria api.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.