【问题标题】:Spring Boot - Jpa RepositorySpring Boot - Jpa 存储库
【发布时间】:2021-11-07 17:29:02
【问题描述】:

我在示例项目中遇到了下面这段代码。如果不正确定义 findItemsById 方法,我无法理解它是如何工作的。此方法在扩展 JpaRepositiry 的 ItemsRepository 接口中声明。

public interface ItemsRepo extends JpaRepository<Items,Long> {
Optional<Items> findItemsById(Long id);
}

在服务类中,它的定义如下所示。

public Items findItemsById(Long id) throws Throwable {
    return itemsRepo.findItemsById(id).orElseThrow(()-> new UserNotFoundException("items by id "+id+" not found"));
}

如果没有 findItemsById 的实际定义,它是如何工作的。将其声明为可选是否与此有任何关系?

【问题讨论】:

  • spring 有一个引擎可以扫描任何扩展 JpaRepository 并为您提供实际类的引擎。
  • @尤金。感谢您的回答。我无法理解“为您提供实际课程”。你能详细说明一下吗?再次感谢
  • @Eugene 再次感谢!

标签: java spring spring-boot spring-data-jpa spring-data


【解决方案1】:

Spring 数据存储库查询派生机制来表达谓词是允许这样做的特性。基本上,查询是通过“解析”方法名称派生的。为此有一些规则(您必须使用实体属性的名称)和关键字(findbycount 等...)。您可以在以下位置查看更多信息:

【讨论】:

    【解决方案2】:

    你最好按Ctrl点击JpaRepository&lt;Items,Long&gt;接口并按照它的方法和它的父方法

    在那里你会看到所有的方法并且你可以理解那些方法

    详细了解可以关注spring docs

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2021-04-16
      • 2015-12-15
      • 1970-01-01
      • 2018-06-26
      • 2017-04-23
      • 2019-01-23
      • 2020-01-21
      • 1970-01-01
      相关资源
      最近更新 更多