2.4.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 have a 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
equalsandhashCodemethods 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 Identity Hierarchies).
|
|
Jakarta Persistence 3.2 no longer requires the identity class to be public or to implement |
|
|
Though you may still create identity classes by hand, OpenJPA provides the |
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;
}
}
}