background image

Primary Keys in Entities

<< Persistent Properties | Multiplicity in Entity Relationships >>
<< Persistent Properties | Multiplicity in Entity Relationships >>

Primary Keys in Entities

Primary Keys in Entities
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 must correspond to either a single persistent property or field, or 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
Floating point types should never be used in primary keys. If you use a generated primary key,
only integral types will be portable.
Primary Key Classes
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, the orderId and itemId fields together
uniquely identify an entity.
Entities
The Java EE 5 Tutorial · September 2007
688