JPA - Primary Key (@Id, @IdClass, ...)

1 - About

Every JPA entity must have a primary key.

A primary key corresponds to one or more fields or properties (“attributes”) of the entity class.

3 - Type

3.1 - Single

A simple (i.e., non-composite) primary key must correspond to a single persistent field or property of the entity class.

The Id annotation or id XML element must be used to denote a simple primary key.


private String myId;

3.2 - Composite

When the database key is composed of several columns, you have to create a composite primary key. It is made up of one or more object types (primitive or JDK)

You can specify such a composite primary key with a separate composite primary key class.

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties.

A primary key class must be defined to represent a composite primary key.

The EmbeddedId or IdClass annotation is used to denote a composite primary key.

A simple primary key or a field or property of a composite primary key should be one of the following types:

  • any Java primitive type (or any primitive wrapper type)
  • java.lang.String
  • java.util.Date
  • java.sql.Date
  • java.math.BigDecimal
  • java.math.BigInteger

If the primary key is a composite primary key derived from the primary key of another entity, the primary key may contain an attribute whose type is that of the primary key of the referenced entity.

Primary key class Rules:

  • must be public and must have a public no-arg constructor.
  • must be serializable
  • define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
  • can be Embedded (EmbeddedId) or not (IdClass)

Annotations Rules:

  • IdClass:
    • The names of primary key fields or properties in the primary key class and those of the entity class to which the id class is mapped must correspond and their types must be the same.
  • EmbeddedId
    • There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation

is used

4 - Generation

4.1 - Table generator

@Id(generate=TABLE, generator="ADDRESS_TABLE_GENERATOR")
public Integer getId() {
    return id;

5 - Documentation / Reference

jpa/primary_key.txt · Last modified: 2017/02/12 21:06 by gerardnico