2.4.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
Personis extended by abstract classEmployee, which is extended by non-abstract classFullTimeEmployee, which is extended by non-abstract classManager. The corresponding identity classes, then, are an abstractPersonIdclass, extended by an abstractEmployeeIdclass, extended by a non-abstractFullTimeEmployeeIdclass, extended by a non-abstractManagerIdclass. -
Subclasses in the identity hierarchy may define additional identity fields until the hierarchy becomes non-abstract. In the aforementioned example,
Persondefines an identity fieldssn,Employeedefines additional identity fielduserName, andFullTimeEmployeeadds a final identity field,empId. However,Managermay 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
PersonandEmployeeclasses could declare no identity fields, and the first concrete subclassFullTimeEmployeecould define one or more identity fields. -
All subclasses of a concrete identity class must be
equalsandhashCode-compatible with the concrete superclass. This means that in our example, aManagerIdinstance and aFullTimeEmployeeIdinstance with the same identity field values should have the same hash code, and should compare equal to each other using theequalsmethod of either one. In practice, this requirement reduces to the following coding practices:-
Use
instanceofinstead of comparingClassobjects in theequalsmethods of your identity classes. -
An identity class that extends another non-abstract identity class should not override
equalsorhashCode.
-