简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM