Hello,
I am trying to use composite PK for my persistence storage. I understand that I can either use @IdClass or @EmbeddedId for my composite primary key. I have two fields in my Entity called "recordID" and "domainID". I want recordID to be @GeneratedValue(GenerationType.AUTO) and domainID to be assigned manually. My domainID may not be unique, but the combination of those two will surely be unique to an object. IS that correct?
Also, does Spring/Hibernate stop us from using @GeneratedValue with Composite PK? Currently, what I am trying to do is:
--------------------------
PK Class
Code:
@Embeddable
public class CompoundPK implements Serializable{
//SerialVersionUID will be here
private long recordID;
private String domainID;
public CompoundKey(){
}
public CompoundKey(String domainID){
this.domainID = domainID;
}
@Column(name = "RECORD_ID")
@GeneratedValue
public long getRecordID(){
return this.recordID;
}
@Column(name = "DOMAIN_ID")
public String getDomainID(){
return this.domainID;
}
public void setRecordID(long recordID){
this.recordID = recordID;
}
public void setDomainID(String domainID){
this.domainID = domainID;
}
/**
* This is where equals, hashCode, and toString method will go
*
**/
}
------------------------------------------------
ENTITY CLASS
Code:
@Entity
@Table(name = "SDS_RECORD")
@XmlRootElement
public class Sds implements Serializable{
//SerialVersionUID
private String details;
private CompoundKey localKey;
public Sds(){
}
public Sds(String details, CompoundKey newKey){
this.details = details;
this.localKey = newKey;
}
@Column(name = "DETAILS")
public String getDetails(){
return this.details;
}
@EmbeddedId
public CompoundKey getKey(){
return this.localKey;
}
// Setters are here
// toString, equals(), hashCode, bla bla bla
}
---------------------
What I am really intersted to know is if the @GeneratedValue actually works fine with composite PK because I tried to do it with @Embeddable and @EmbeddedId but it did not increment the recordiD and therefore, the composite PK was not unique. I got a recordID as '0' and a domainID as "DOM1". I also tried to persist 3 objects where each of them had the same domainID, but expected to have three different recordIDs so that the combinations are unique to respective objects. domainID on itself should not matter whereas the combination of those two do. Could someone please help me?