Spring Data Rest是否支持JPARepository的Example查询方法及变体?
当然支持啦!Spring Data Rest 完全兼容 QueryByExampleExecutor 接口中的所有基于 Example 的查询方法,包括你提到的 <S extends T> Page<S> findAll(Example<S> example, Pageable pageable)。
下面给你拆解一下具体的支持情况和使用方式:
核心支持范围:只要你的 Repository 继承了
JPARepository(而JPARepository本身已经继承了QueryByExampleExecutor),Spring Data Rest 就会自动为这些Example相关方法生成对应的 REST 端点。除了你问的分页方法,像findAll(Example<S> example)、findOne(Example<S> example)这类基础方法也都支持。如何在REST请求中传递Example参数:你不需要手动构建
Example对象,Spring Data Rest 会自动把请求中的查询参数转换为Example实例。举个例子,假设你有一个User实体,包含firstname和lastname字段,你可以这样发起请求:GET /users?page=0&size=10&firstname=John&lastname=Doe这个请求会自动触发
findAll(Example<User>, Pageable)方法,其中Example会包含firstname=John和lastname=Doe的匹配条件,同时应用分页参数。匹配策略细节:默认情况下,
Example对字符串类型字段会使用模糊匹配(相当于SQL的LIKE %value%),对其他类型(比如数字、日期)会使用精确匹配。如果你需要调整匹配策略,可以通过自定义ExampleMatcher并在Repository中定义对应的方法,也可以通过请求参数的特殊语法来指定匹配规则(比如用firstname:John来指定精确匹配)。
需要注意的是,这些基于 Example 的方法都是自动支持的,不需要额外的配置,只要你的Repository继承关系正确即可。
内容的提问来源于stack exchange,提问作者Shamal Karunarathne

