Answers:
您可以制作一个Embedded class
,其中包含两个键,然后像EmbeddedId
中一样引用该类Entity
。
您将需要@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;
}
@Generatedvalue
EmbeddedId用作ID?
@GeneratedValue
只能用于为主键生成键值,而不能为组合键生成组合键。
关键类别:
@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的键,然后将其持久保存为新实体。
AUTOGENERATED
。像这样的事情 @GeneratedValue(strategy = GenerationType.IDENTITY)
hash
和prime
在方法hashCode
在课堂上EntryKey
,你能告诉我这种想法从何而来?
@IdClass
注解时,我发现的另一个技巧是@Column
注解应进入Entity类的字段(YourEntity
在RohitJan的示例代码中)。