为什么 Entity 类 必须有一个@Id?

Why do Entity classes must have an @Id?

我对此有点困惑。当我尝试创建一个没有@Id 的实体时,编译时给我一个错误,我必须设置主键使用@Id,我什至无法将应用程序部署到应用程序服务器(我使用 payara)。但是官方 Java EE 7 教程文档中对实体 类 的要求不包含实体必须具有 @Id 的规则。并且,该文档中实体的定义:

Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.

但我可以创建一个没有主键的数据table。

所以我的问题实际上是为什么我们必须在实体中设置@Id。还有其他的考虑吗?例如,使用@Id 来标识持久化上下文中的特定实体,这样我们就可以使用em.find(id)?还有如果我非要创建一个没有@Id的实体怎么办,哈哈

感谢您的帮助。

实体是您存储在数据库中的东西(我无法想出您不这样做的用例)。您存储在数据库 table 中的内容需要有一个主键。对于主键,我们一般使用Id。

我很确定你收到的警告是添加的“你确定你没有忘记什么吗?” IDE 的功能,可以在设置中禁用。

JPA 实体 bean 需要以一种或另一种方式指定主键。

来自 JSR 338:JavaTM 持久性 API,版本 2.1 规范

2.4 Primary Keys and Entity Identity:

Every entity must have a primary key.

The primary key must be defined on the entity class that is the root of the entity hierarchy or on a mapped superclass that is a (direct or indirect) superclass of all entity classes in the entity hierarchy. The primary key must be defined exactly once in an entity hierarchy.

A primary key corresponds to one or more fields or properties (“attributes”) of the entity class.
...

如果我谈论数据库,每个 table 都应该有一些列(或列) 可以唯一标识特定行。

以同样的方式,因为我们的实体 class 代表一个 table,所以那里非常需要 @Id

(我的回答只是给那些初学者的提示。)