[英]How to create and handle composite primary key in JPA
我想擁有來自相同數據條目的版本。 換句話說,我想用另一個版本號復制該條目。
id - Version
將是主鍵。
該實體應該如何? 如何與其他版本復制?
id Version ColumnA
1 0 Some data
1 1 Some Other data
2 0 Data 2. Entry
2 1 Data
您可以創建一個包含兩個鍵的Embedded class
,然后在您的Entity
引用該類作為EmbeddedId
。
您需要@EmbeddedId
和@Embeddable
注釋。
@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
注釋
@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;
}
如果您使用@IdClass
,MyKey類必須實現Serializable
關鍵課程:
@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {
public EntryKey() {
}
public EntryKey(final Long id, final Long version) {
this.id = id;
this.version = version;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
this.version = version;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof EntryKey))
return false;
EntryKey castOther = (EntryKey) other;
return id.equals(castOther.id) && version.equals(castOther.version);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.id.hashCode();
hash = hash * prime + this.version.hashCode();
return hash;
}
@Column (name = "ID")
private Long id;
@Column (name = "VERSION")
private Long operatorId;
}
實體類:
@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {
@EmbeddedId
public EntryKey getKey() {
return this.key;
}
public void setKey(EntryKey id) {
this.id = id;
}
...
private EntryKey key;
...
}
如何與其他版本復制?
您可以分離從提供程序檢索的實體,更改Entry的鍵,然后將其作為新實體保留。
MyKey類(@Embeddable)不應該有像@ManyToOne這樣的任何關系
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.