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());
}