Skip to content
Advertisement

Spring data jpa, how to filter and then sort results in this example?

I wrote a method, but as you can see – Category here is never used.

Is to possible to find only Dishes where Category is same as defined and only after it – sort it by parameter using plain Spring data jpa? Or the only way to it is a custom query?

public List<Dish> findAllDishesSorted(String sortField, String sortDirection, String category) {
    Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
            ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();

            return dishRepository.findAll(sort);
}

Advertisement

Answer

You could add a method like below to your DishRepository and it should be able to achieve that without needing to write custom query with @Query() annotation

public interface DishRepository extends CrudRepository<Dish, Long> {
    Dish findByCategory(String category, Sort sort);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement