简体   繁体   English

Spring 数据 jpa,在这个例子中如何过滤然后排序结果?

[英]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?是否可以仅找到类别与定义相同且仅在其之后的菜肴 - 使用普通 Spring 数据 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您可以在DishRepository中添加如下所示的方法,它应该能够实现这一点,而无需使用@Query()注释编写自定义查询

public interface DishRepository extends CrudRepository<Dish, Long> {
    Dish findByCategory(String category, Sort sort);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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