如何在JPA中创建和处理复合主键 [英] How to create and handle composite primary key in JPA
问题描述
我想拥有来自同一数据条目的版本。换句话说,我想用另一个版本号复制该条目。
I want to have versions from the same data entry. In other words, I want to duplicate the entry with another version number.
id - Version
将是主要的键。
实体应该如何?如何与其他版本复制?
How should the entity look like? How can I duplicate it with another version?
id Version ColumnA
1 0 Some data
1 1 Some Other data
2 0 Data 2. Entry
2 1 Data
推荐答案
您可以创建一个嵌入式类
,其中包含您的两个键,然后将该类引用为<$ 实体
中的c $ c> EmbeddedId 。
You can make an Embedded class
, which contains your two keys, and then have a reference to that class as EmbeddedId
in your Entity
.
您需要 @EmbeddedId
和 @Embeddable
注释。
You would need the @EmbeddedId
and @Embeddable
annotations.
@Entity
public class YourEntity {
@EmbeddedId
private MyKey myKey;
@Column(name = "ColumnA")
private String columnA;
/** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {
@Column(name = "Id", nullable = false)
private int id;
@Column(name = "Version", nullable = false)
private int version;
/** getters and setters **/
}
实现此任务的另一种方法是使用 @IdClass
注释,并放置 id
在 IdClass
中。现在你可以在两个属性上使用普通的 @Id
注释
Another way to achieve this task is to use @IdClass
annotation, and place both your id
in that IdClass
. Now you can use normal @Id
annotation on both the attributes
@Entity
@IdClass(MyKey.class)
public class YourEntity {
@Id
private int id;
@Id
private int version;
}
public class MyKey implements Serializable {
private int id;
private int version;
}
这篇关于如何在JPA中创建和处理复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!