You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data Rest技术问题:CrudRepository方法未暴露及404异常咨询

Spring Data Rest 常见问题解答

问题1:为何Spring Data Rest不暴露CrudRepository的findAll、findById等方法到/search路径?

CrudRepository的findAll、findById这类方法属于基础CRUD操作,Spring Data Rest并没有将它们归类为“搜索方法”,而是直接映射到了资源的根路径:

  • findAll 对应 GET /rest-api/users(直接返回所有用户资源)
  • findById 对应 GET /rest-api/users/{id}(根据ID返回单个资源)

/search 路径专门用于暴露自定义查询方法——也就是你在Repository中手动定义的、带有筛选条件的查询(比如示例中的getByEmail、existsByEmail)。这类方法需要遵循Spring Data的命名规则(如findByXXX、getByXXX),或者通过@Query注解自定义SQL,Spring Data Rest才会将其注册到/search下作为可调用的搜索端点。

问题2:访问/apps/search返回404的原因

出现404是因为你的AppRepository中没有定义任何符合暴露规则的自定义查询方法。

Spring Data Rest生成/search端点的前提是:Repository中存在自定义的查询方法(比如findByName(String name)、getByAppKey(String key)这类带参数的查询,或者用@Query标注的自定义SQL方法)。如果AppRepository仅仅继承了CrudRepository或JpaRepository,没有添加任何自定义查询逻辑,那么Spring Data Rest不会为它创建/search路径,访问自然会返回ResourceNotFoundException。

解决方法:检查AppRepository的代码,添加至少一个自定义查询方法,比如:

public interface AppRepository extends CrudRepository<App, Long> {
    // 示例:添加一个按名称查询的方法
    List<App> findByName(String name);
}

添加后重启项目,/rest-api/apps/search就会正常返回该查询方法的链接了。


内容的提问来源于stack exchange,提问作者AMZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:35:28