MS13
MS13

Reputation: 397

Example of spring using Pageable, Example and Sort accessing a JPA repository

I searched everywhere for an example of a Spring piece of code using simultaneously these 3 JPA concepts, very important when querying :

So far I only saw examples using only 2 of them at the same time but I need to use all of them at once. Can you show me such an example?

Thank you.

PS: This has examples for Paging and Sorting but not filtering.

Upvotes: 2

Views: 5696

Answers (2)

MS13
MS13

Reputation: 397

Found the answer in the end after more research:

public Page<MyEntity> findAll(MyEntity entityFilter, int pageSize, int currentPage){
    ExampleMatcher matcher = ExampleMatcher.matchingAll()
        .withMatcher("name", exact()); //add filters for other columns here
    Example<MyEntity> filter = Example.of(entityFilter, matcher); 
    Sort sort = Sort.by(Sort.Direction.ASC, "id"); //add other sort columns here
    Pageable pageable = PageRequest.of(currentPage, pageSize, sort); 
    return repository.findAll(filter, pageable);
}

Upvotes: 2

Yann39
Yann39

Reputation: 15729

Here is an example, searching for news on title attribute, with pagination and sorting :

Entity :

@Getter
@Setter
@Entity
public class News {

    @Id
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

}

Repository :

public interface NewsRepository extends JpaRepository<News, Long> {

}

Service

@Service
public class NewsService {

    @Autowired
    private NewsRepository newsRepository;

    public Iterable<News> getNewsFilteredPaginated(String text, int pageNumber, int pageSize, String sortBy, String sortDirection) {

        final News news = new News();
        news.setTitle(text);

        final ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreCase()
                .withIgnorePaths("content")
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

        return newsRepository.findAll(Example.of(news, matcher), PageRequest.of(pageNumber, pageSize, sortDirection.equalsIgnoreCase("asc") ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending()));

    }
}

Call example :

for (News news : newsService.getNewsFilteredPaginated("hello", 0, 10, "title", "asc")) {
    log.info(news.getTitle());
}

Upvotes: 3

Related Questions