Each entity has a unique object identifier. A customer entity, for example, might be identified by a customer number. The unique identifier, or primary key, enables clients to locate a particular entity instance. Every entity must have a primary key. An entity may have either a simple or a composite primary key.
Simple primary keys use the javax.persistence.Id annotation to denote the primary key property or field.
Composite primary keys are used when a primary key consists of more than one attribute, which corresponds to a set of single persistent properties or fields. Composite primary keys must be defined in a primary key class. Composite primary keys are denoted using the javax.persistence.EmbeddedId and javax.persistence.IdClass annotations.
The primary key, or the property or field of a composite primary key, must be one of the following Java language types:
Java primitive types
Java primitive wrapper types
java.lang.String
java.util.Date (the temporal type should be DATE)
java.sql.Date
java.math.BigDecimal
java.math.BigInteger
Floating-point types should never be used in primary keys. If you use a generated primary key, only integral types will be portable.
A primary key class must meet these requirements.
The access control modifier of the class must be public.
The properties of the primary key class must be public or protected if property-based access is used.
The class must have a public default constructor.
The class must implement the hashCode() and equals(Object other) methods.
The class must be serializable.
A composite primary key must be represented and mapped to multiple fields or properties of the entity class or must be represented and mapped as an embeddable class.
If the class is mapped to multiple fields or properties of the entity class, the names and types of the primary key fields or properties in the primary key class must match those of the entity class.
The following primary key class is a composite key, and the orderId and itemId fields together uniquely identify an entity:
public final class LineItemKey implements Serializable { public Integer orderId; public int itemId; public LineItemKey() {} public LineItemKey(Integer orderId, int itemId) { this.orderId = orderId; this.itemId = itemId; } public boolean equals(Object otherOb) { if (this == otherOb) { return true; } if (!(otherOb instanceof LineItemKey)) { return false; } LineItemKey other = (LineItemKey) otherOb; return ( (orderId==null?other.orderId==null:orderId.equals (other.orderId) ) && (itemId == other.itemId) ); } public int hashCode() { return ( (orderId==null?0:orderId.hashCode()) ^ ((int) itemId) ); } public String toString() { return "" + orderId + "-" + itemId; } }