Java Reference
In-Depth Information
Generating persistent identifiers
First you must pick an identifier-generation strategy. Hibernate, like JDO , can gen-
erate the persistent identifier for your objects, or it can allow your application to
generate them. Application-generated persistent identifiers are useful when the
application needs precise control over the object's primary key. For example, one
common reason to use application-assigned identifiers is if you are working with a
legacy schema that uses a natural key as the primary key. In this situation, the appli-
cation must assign a primary key value to an object before calling Session.save() .
Most of the time, however, it is a lot more convenient to let Hibernate generate
an object's persistent identity, especially because it is good practice to use surro-
gate instead of natural keys. You also have less code to write. Hibernate provides
several identifier-generation strategies, including Oracle sequences, identity col-
umns, and Unique Universal Identifier ( UUID ) generation algorithms. The best
approach is to configure Hibernate to use the native generation strategy, as illus-
trated by the earlier example. Hibernate picks the most appropriate strategy for
the database. For example, Hibernate uses sequences for an Oracle database and
identity columns for an HSQLDB database. Native generation is extremely useful
because it enables the O/R mapping to be portable across databases. You can, for
example, test against HSQLDB and then deploy on Oracle without changing the
O/R mapping document.
Using identifier properties
In addition to deciding how to generate identifiers, you must determine whether
you need to define an identifier property in which to store them. The class must
have an identifier property if it uses an application-generated primary key because
it must be able to assign a value to the property before saving the object. An iden-
tifier property is optional if Hibernate is responsible for generating identifiers. If
an object has an identifier property, Hibernate assigns the generated identifier to
it when the object is saved.
As we described in chapter 5 when comparing JDO datastore identity and
application identity, the main benefit of identifier properties is that they make an
object's persistent identity readily available to the rest of the application. They are
extremely useful when the business tier returns domain objects to the presenta-
tion tier, which typically embeds object identifiers in URL s or hidden fields or
stores them as part of the session state. If an object has an identifier property, the
presentation tier can easily get an object's identifier. However, if an object does
not have an identifier property, either the business tier or presentation tier must
 
 
Search WWH ::




Custom Search