Java Reference
In-Depth Information
model objects may utilize address information, and instead of duplicating those properties,
an @Embeddable Address object may be created and @Embedded used in your Java
domain model. We invite you to further explore the @Embedded , @Embeddable , and
@AttributeOverride annotations on your own.
Now that you know how to map primary keys to the Java domain model, let's take a look
at how JPA can generate primary keys when inserting data into the database.
9.3.8. Generating primary keys
In the previous section you learned how to map database primary keys to the Java domain
model. In the simplest case, you use the @Id annotation to map a single-column primary
key. In more complicated cases, you use either @IdClass or @EmbeddedId to map
multiple-column primary keys. But we've yet to discuss how the primary-key values are
generated.
When generating primary keys, there are typically two schools of thought. The first is that
primary keys should arise naturally from the data. For example, when storing user data it
may be sufficient to say that a person's first name, last name, and telephone number are
enough to uniquely identify a row in the table. Therefore, the primary key should consist of
these three columns. The second school of thought is to introduce artificial data that's not
related in any way to the data being stored and exists only to uniquely identify rows in the
table. These are typically sequenced, numbered, single-column, primary keys.
Although there are pros and cons associated with each technique, in general, the introduc-
tion of artificial data to serve as the primary key is most conventional. There are five pop-
ular ways of generating primary-key values like this:
• Auto
• Identity
• Sequence
• Table
• Code
Search WWH ::




Custom Search