2. Entity Identity
Prev | Chapter 4. Entity | Next

## 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, `String`s, `Date`s, `Timestamp`s, or embeddable types.

### Note

OpenJPA supports entities as identity fields, as the Reference Guide discusses in Section 4.2, “ 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.

### 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 Section 3, “ 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.

### 2.1. Identity Class

If your entity has only one identity field, you can use the value of that field as the entity's identity object in all `EntityManager` APIs. Otherwise, you must supply an identity class to use for identity objects. Your identity class must meet the following criteria:

- The class must be public.

- The class must be serializable.

- The class must have a public no-args constructor.

- The names of the non-static fields or properties of the class must be the same as the names of the identity fields or properties of the corresponding entity class, and the types must be identical.

- The `equals` and `hashCode` methods of the class must use the values of all fields or properties corresponding to identity fields or properties in the entity class.

- If the class is an inner class, it must be `static`.

- All entity classes related by inheritance must use the same identity class, or else each entity class must have its own identity class whose inheritance hierarchy mirrors the inheritance hierarchy of the owning entity classes (see Section 2.1.1, “ Identity Hierarchies ”).

### Note

Though you may still create identity classes by hand, OpenJPA provides the `appidtool` to automatically generate proper identity classes based on your identity fields. See Section 4.3, “ Application Identity Tool ” of the Reference Guide.

Example 4.2. Identity Class

This example illustrates a proper identity class for an entity with multiple identity fields.

    /**
     * Persistent class using application identity.
     */
    public class Magazine {

        private String isbn;    // identity field
        private String title;   // identity field

        // rest of fields and methods omitted

        /**
         * Application identity class for Magazine.
         */
        public static class MagazineId {

            // each identity field in the Magazine class must have a
            // corresponding field in the identity class
            public String isbn;
            public String title;

            /**
             * Equality must be implemented in terms of identity field
             * equality, and must use instanceof rather than comparing
             * classes directly (some JPA implementations may subclass the
             * identity class).
             */
            public boolean equals(Object other) {
                if (other == this)
                    return true;
                if (!(other instanceof MagazineId))
                    return false;

                MagazineId mi = (MagazineId) other;
                return (isbn == mi.isbn
                    || (isbn != null && isbn.equals(mi.isbn)))
                    && (title == mi.title
                    || (title != null && title.equals(mi.title)));
            }

            /**
             * Hashcode must also depend on identity values.
             */
            public int hashCode() {
                return ((isbn == null) ? 0 : isbn.hashCode())
                    ^ ((title == null) ? 0 : title.hashCode());
            }

            public String toString() {
                return isbn + ":" + title;
            }
        }
    }

#### 2.1.1. Identity Hierarchies

An alternative to having a single identity class for an entire inheritance hierarchy is to have one identity class per level in the inheritance hierarchy. The requirements for using a hierarchy of identity classes are as follows:

- The inheritance hierarchy of identity classes must exactly mirror the hierarchy of the persistent classes that they identify. In the example pictured above, abstract class `Person` is extended by abstract class `Employee`, which is extended by non-abstract class `FullTimeEmployee`, which is extended by non-abstract class `Manager`. The corresponding identity classes, then, are an abstract `PersonId` class, extended by an abstract `EmployeeId` class, extended by a non-abstract `FullTimeEmployeeId` class, extended by a non-abstract `ManagerId` class.

- Subclasses in the identity hierarchy may define additional identity fields until the hierarchy becomes non-abstract. In the aforementioned example, `Person` defines an identity field `ssn`, `Employee` defines additional identity field `userName` , and `FullTimeEmployee` adds a final identity field, `empId`. However, `Manager` may not define any additional identity fields, since it is a subclass of a non-abstract class. The hierarchy of identity classes, of course, must match the identity field definitions of the persistent class hierarchy.

- It is not necessary for each abstract class to declare identity fields. In the previous example, the abstract `Person` and `Employee` classes could declare no identity fields, and the first concrete subclass `FullTimeEmployee` could define one or more identity fields.

- All subclasses of a concrete identity class must be `equals` and `hashCode`-compatible with the concrete superclass. This means that in our example, a `ManagerId` instance and a `FullTimeEmployeeId` instance with the same identity field values should have the same hash code, and should compare equal to each other using the `equals` method of either one. In practice, this requirement reduces to the following coding practices:

  1. Use `instanceof` instead of comparing `Class` objects in the `equals` methods of your identity classes.

  2. An identity class that extends another non-abstract identity class should not override `equals` or `hashCode`.

Prev | Up | Next
Chapter 4. Entity | Home | 3. Lifecycle Callbacks