我创建了一个使用@Id 指向@Embeddable 复合键的实体。我相信的一切都可以正常工作。但是,在将 @Id 切换为 @EmbeddedId 之后,据我所知,一切都继续正常工作。
之前:
@Entity
public final class MyEntity {
private CompoundKey id;
@Id
public CompoundKey getId() {
return id;
}
public void setId(CompoundKey id) {
this.id = id;
}
之后:
@Entity
public final class MyEntity {
private CompoundKey id;
@EmbeddedId
public CompoundKey getId() {
return id;
}
public void setId(CompoundKey id) {
this.id = id;
}
在引用复合键时使用@Id 和@EmbeddedId 注释有区别吗?
最佳答案
我真的很惊讶 “之前” 版本可以正常工作。根据规范,映射 Embeddable
复合键的正确方法是 "after" 版本。引用 JPA 1.0 规范:
2.1.4 Primary Keys and Entity Identity
Every entity must have a primary key.
The primary key must be defined on the entity that is the root of the entity hierarchy or on a mapped superclass of the entity hierarchy. The primary key must be defined exactly once in an entity hierarchy.
A simple (i.e., non-composite) primary key must correspond to a single persistent field or property of the entity class. The
Id
annotation is used to denote a simple primary key. See section 9.1.8.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 below. 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
and andIdClass
annotations are used to denote composite primary keys. See sections 9.1.14 and 9.1.15.The primary key (or field or property of a composite primary key) should be one of the following types: any Java primitive type; any primitive wrapper type;
java.lang.String
;java.util.Date
;java.sql.Date
. In general, however, approximate numeric types (e.g., floating point types) should never be used in primary keys. Entities whose primary keys use types other than these will not be portable. If generated primary keys are used, only integral types will be portable. Ifjava.util.Date
is used as a primary key field or property, the temporal type should be specified as DATE....
后来:
9.1.14 EmbeddedId Annotation
The
EmbeddedId
annotation is applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated asEmbeddable
.There must be only one
EmbeddedId
annotation and no Id annotation when theEmbeddedId
annotation is used.
关于java - 使用 @Id 和 @EmbeddedId 作为复合键的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3868515/