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

Time:01-20

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

CodePudding user response:

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);
}
  •  Tags:  
  • Related