在 Spring 数据休息中自定义分页和排序的查询

acv*_*vcu 6 java spring spring-data spring-data-rest

我正在使用 Spring 数据休息,并尝试findAll使用@Query. 但是,当我尝试这样做时,我收到此错误:

java.lang.IllegalStateException:检测到不明确的搜索映射。公共抽象 org.springframework.data.domain.Pagecourses.CourseRepository.findAll(org.springframework.data.domain.Pageable) 和公共抽象 java.lang.Iterablecourses.CourseRepository.findAll(org.springframework.data.domain. Sort) 映射到 /findAll! 调整配置以获得明确的路径!

当调用这些方法时,URL/findAll按照惯例不包含。检索未分类课程(但使用分页)的 URL 是

http://localhost:8080/v1/courses

和排序是

http://localhost:8080/v1/courses?sort=title

这是相关的代码,它相当简单:

public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {

  @Override
  @Query("SELECT c FROM Course c WHERE c.visible = 'Yes'")
  Page<Course> findAll(Pageable pageable);

  @Override
  @Query("SELECT c FROM Course c WHERE c.visible = 'Yes'")
  Iterable<Course> findAll(Sort sort);
}
Run Code Online (Sandbox Code Playgroud)

我还尝试@NamedQuery在 Course 实体上使用具有相同错误消息的 。

编辑:

我发现该findAll(Pageable pageable)方法具有“内置”排序功能,但它不会对结果进行排序。当我点击以下 URL 并尝试按标题排序时,结果显然不是按标题排序的。但是,如果没有自定义@Query,结果将被排序。

http://localhost:8080/v1/courses?sort=title

Sha*_*aan 2

我猜你正在尝试重载findAllSpring-Data 的方法。这只能通过 来实现CustomRepository

这是一个有用的链接,可指导您创建CustomRepository.

您可以使用自定义方法定义一个类,以便根据需要调整 Spring-Data 的方法。

Spring 文档链接相同