Java Reference
In-Depth Information
An object representing an entity will have a normal Java class type. It will also have an
entity name. By default, the name of the entity will be the same as the name of the class type.
You have the option, however, to change this via the mappings, and thus distinguish between
objects of the same type that are mapped to different tables. There are therefore methods in
the Session API that require an entity name to be provided to determine the appropriate map-
ping. If this is omitted, it will either be because no such distinction is needed, or because, for
convenience, the method assumes the most common case—in which the entity name is the
same as the class name—and duplicates the functionality of another more specific method
that permits the entity name to specified explicitly.
Identifiers
Hibernate requires all entities to have an identifier, which represents the primary key col-
umn(s) of the table to which it will be persisted. When an entity is persisted, a suitable
identifier can be assigned to it automatically by Hibernate, or a suitable identifier may be
explicitly assigned by the user (see Listing 4-1).
Listing 4-1. A Typical Identifier Field
public int id;
Usually, the entity will provide a suitable identifier field or property, and Hibernate will
use this value to correlate entities in memory with those persisted to the tables of the data-
base. However, if no such field or property is available (as will likely be the case with legacy
code), then Hibernate itself can manage the identifier value internally. The type of the identi-
fier must be defined in the mapping information.
Entities and Associations
Entities can contain references to other entities—either directly as a property or field, or indi-
rectly via a collection of some sort (arrays, sets, lists, etc.). These associations are represented
using foreign key relationships in the underlying tables.
When only one of the pair of entities contains a reference to the other, the association is
unidirectional. If the association is mutual, then it is referred to as bidirectional.
n Tip A common mistake when designing entity models using Hibernate is to try to make all associations
bidirectional. Associations that are not a natural part of the object model should not be forced into it. HQL
often presents a more natural way to access the same information.
If both ends of the association managed the foreign keys, then we would encounter a prob-
lem when client code called the appropriate set method on both ends of the association. Should
two foreign key columns be maintained—one in each direction (risking circular dependencies)—
or only one? (And if only one, should altering either side affect it, or only one?)
Search WWH ::




Custom Search