Java Reference
In-Depth Information
In this listing, there's first a @TableGenerator with name set to USER_TABLE
_GENERATOR . This is the internal JPA name for this sequence, and other JPA annota-
tions will use this name when referring to the sequence. The table attribute is set to the
name of the table . The pkColumnName attribute is the name of the column in the
table that holds the names of the sequences . The valueColumnName attribute is the
name of the column that holds the values of the sequences . Finally, the pkColumn-
Value attribute is the name of the sequence you wish to use (see the insert statement
of listing 9.14 ) . For the @GeneratedValue annotation, the strategy is set to Gen-
erationType.TABLE
and the generator is set to the internal JPA name of the
strategy
.
Remember that @TableGenerator is sharable across the entire persistence unit. This
means a @TableGenerator doesn't need to be defined in the class it's used. Any
@TableGenerator is shared among all entities, so keep that in mind when assigning
internal JPA names to ensure they're unique.
Primary keys, equals(), and hashCode()
It's important to point out that the special relationship primary-key values have to the
equals() and hashCode() methods. Typically these methods are overridden to com-
pare Java domain model objects by primary-key values. But in any auto-generation key
strategy, the primary-key value won't be known until the persistence manager inserts the
data into the database. Before the insert happens, the primary-key value in your domain
model object will be NULL . Therefore, equals() and hashCode() must be able to
handle null values gracefully.
Code
The code strategy is for situations when you don't want the database to auto-generate a
primary key. Instead, you want to generate the primary key yourself in your application's
code. This is achievable with JPA using various techniques, but the most popular one is to
use the @PrePersist lifecycle annotation to set the value of the primary-key property
before the data is inserted into the database. The following listing shows what the User
object may look like using the code strategy.
Search WWH ::




Custom Search