Hibernate 是否仅支持在数据库中定义的显式主键

Does Hibernate only support explicit primary keys defined at the database

我正在使用遗留数据库,其中没有为表定义明确定义的主键。相反,已使用多个列来定义表中行的唯一性约束。简而言之,这些列形成一个复合键,可以被视为表的隐式主键。我正在考虑使用将唯一性约束定义为实体主键的列来定义复合键。这会在 Hibernate 中工作吗?我担心由于没有为表定义主键,Hibernate 在为这些表创建实体时会失败

Hibernate 实现了 JPA specification,它明确允许复合主键,只要它们是不可变的:

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

  • A simple (i.e., non-composite) primary key must correspond to a single persistent field or property of the entity class. The Id annotation or id XML element must be used to denote a simple primary key.
  • A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described be low. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId or IdClass annotation is used to denote a composite primary key.

The value of its primary key uniquely identifies an entity instance within a persistence context and to EntityManager operations as described in Chapter 3, “Entity Operations”. The application must not change the value of the primary key. The behavior is undefined if this occurs.