In Java JPA, you can define composite keys of using the @EmbeddedId annotation. For example, you have a table called contact and you want to use the columns firstname and lastname as the composite keys.
Firstly, you need to create ContactPK as the primary key class of Entity Contact.
ContactPK.java
@Embeddable
public class ContactPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column (name = "firstname")
private String firstname;
@Column (name = "lastname")
private String lastname;
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
Then you can create the Entity Contact with ContactPK as the primary key.
Contact.java
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private ContactPK contactPK;
public ContactPK getContactPK() {
return this.contactPK;
}
public void setContactPK(ContactPK contactPK) {
this.contactPK = contactPK;
}
}
Done =)
Reference: Using Composite Keys with JPA
