How to create and handle composite primary key in JPA
The MyKey class must implement Serializable
if you are using @IdClass
You can make an Embedded class
, which contains your two keys, and then have a reference to that class as EmbeddedId
in your Entity
.
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 **/
}
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;
}
Key class:
@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 class:
@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;
...
}
How can I duplicate it with another Version?
You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.
The MyKey class (@Embeddable) should not have any relationships like @ManyToOne