2.4.2. Entity Identity

Java recognizes two forms of object identity: numeric identity and qualitative identity. If two references are numerically identical, then they refer to the same JVM instance in memory. You can test for this using the == operator. Qualitative identity, on the other hand, relies on some user-defined criteria to determine whether two objects are "equal". You test for qualitative identity using the equals method. By default, this method simply relies on numeric identity.

JPA introduces another form of object identity, called entity identity or persistent identity. Entity identity tests whether two persistent objects represent the same state in the datastore.

The entity identity of each persistent instance is encapsulated in its identity field(s). If two entities of the same type have the same identity field values, then the two entities represent the same state in the datastore. Each entity’s identity field values must be unique among all other entities of the same type.

Identity fields must be primitives, primitive wrappers, Strings, Dates, Timestamps, UUIDs or embeddable types.

Note

OpenJPA supports entities as identity fields, as the Reference Guide discusses in Entities as Identity Fields. For legacy schemas with binary primary key columns, OpenJPA also supports using identity fields of type byte[]. When you use a byte[] identity field, you must create an identity class. Identity classes are covered below.

Note

OpenJPA supports UUIDs identity fields using the binary representation of UUID on the database if the database and its JDBC driver supports it. When this conditions are not met, it uses the canonical string representation of the UUID.

Warning

Changing the fields of an embeddable instance while it is assigned to an identity field has undefined results. Always treat embeddable identity instances as immutable objects in your applications.

If you are dealing with a single persistence context (see Persistence Context), then you do not have to compare identity fields to test whether two entity references represent the same state in the datastore. There is a much easier way: the == operator. JPA requires that each persistence context maintain only one JVM object to represent each unique datastore record. Thus, entity identity is equivalent to numeric identity within a persistence context. This is referred to as the uniqueness requirement.

The uniqueness requirement is extremely important - without it, it would be impossible to maintain data integrity. Think of what could happen if two different objects in the same transaction were allowed to represent the same persistent data. If you made different modifications to each of these objects, which set of changes should be written to the datastore? How would your application logic handle seeing two different "versions" of the same data? Thanks to the uniqueness requirement, these questions do not have to be answered.