Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Slice with findAll method : Spring Data

What i want : skip the count query that spring performs with findAll(Pageable).

I found that there is Slice datatype for such UIs (next based) where there is no need for total records/pages hence no need for count query.

I can use Slice return type for methods like findByName(Pageable) etc but if i use Slice for findAll(Pageable) then it still performs the count query.

Is there a workaround where i am able to use slice for findAll avoiding the count query?

P.S. : i want the features that slice provide like - hasNext, size etc and i don't need to use Specification as well.

Any help is appreciated.

like image 805
Sachin Sharma Avatar asked Oct 25 '16 11:10

Sachin Sharma


People also ask

What does the findAll method returns in spring JPA?

The List<Todo> findAll() method returns all Todo objects that are found from the database. The Optional<Todo> findOne(Long id) method finds the todo entry whose id is given as a method parameter.

What is the difference between Findby and findAll in JPA?

No, there is no difference between them, they will execute exactly the same query, the All part is ignored by Spring Data when deriving the query from the method name.

Can findAll return null?

findAll. Returns all entities matching the given Specification and Sort . Parameters: spec - can be null.


2 Answers

It is possible to use Slice with findAll() - you just need to extend the correct Spring JPA Repository.

It won't work if you extend JpaRepository, because it extends PagingAndSortingRepository and there's already findAll(Pageable pageable) method defined in the Paging repository.

If you extend CrudRepository then you will be able to define method Slice<T> findAll(Pageable pageable) in your repository.

like image 67
hovanessyan Avatar answered Oct 05 '22 09:10

hovanessyan


You can use query derivation for this. Based on a Spring Data JPA examples:

/**
 * Returns a {@link Slice} counting a maximum number of {@link Pageable#getPageSize()} users matching given criteria
 * starting at {@link Pageable#getOffset()} without prior count of the total number of elements available.
 * 
 * @param lastname
 * @param page
 * @return
 */
Slice<User> findByLastnameOrderByUsernameAsc(String lastname, Pageable page);

You can modify this to your needs by adding the following to your repository:

Slice<User> findBy(Pageable page);

Since it doesn't have any other condition it performs a findAll limited to a single page, but without a count query.

like image 25
Jens Schauder Avatar answered Oct 05 '22 10:10

Jens Schauder