CrudRepository 是如何知道从哪个 table 获取数据的呢?

How does CrudRepository know which table to get data?

我使用 Angular、SpringBoot 和 MySQL 数据库构建了一个应用程序。 它使用 CrudRepository 但我不明白它(一切正常)。 controllers/repository 如何知道从哪个 table 获取数据?我的意思是,我没有指定 table 名称。 谁能给我解释一下这是怎么回事?

当您扩展 CrudRepository 时,您定义了它的通用类型。在这里,您可以告诉存储库将从哪个 Entity class 获取数据。而JPA中的Entityclass就是用来表示Tables的。这就是它知道从哪里获取数据的方式。例如:

public interface UserRepository extends CrudRepository<User, Long>  {
}

在上面的代码中,我指定泛型类型为User,另外User是我的实体class,代表users table我的 database。所以这个 Repository 将处理 users table.

在 spring 引导数据 JPA 应用程序中,任何模型都使用 @Entity@Table(name = "User") 进行注释。如果是前者,默认的 table 名称与实体名称相同。

此外,当您创建任何存储库时,例如: public interface UserRepository extends CrudRepository<User, Long> 实体的默认实现,即用户被称为以通用方式执行所有操作。

我发现以下解释很有帮助,因为它遍历了 @Entity@Table 的所有可能组合并列出了相应的查询。
https://walkingtechie.blogspot.com/2019/06/difference-between-entity-and-table.html