background image

Generated Primary Keys

<< One-to-Many Relationship | LineItemKey Class >>
<< One-to-Many Relationship | LineItemKey Class >>

Generated Primary Keys

Primary Keys in the order Application
The order application uses several types of primary keys: single-valued primary keys,
compound primary keys, and generated primary keys.
Generated Primary Keys
VendorPart
uses a generated primary key value. That is, the application does not assign primary
key values for the entities, but instead relies on the persistence provider to generate the primary
key values. The @GeneratedValue annotation is used to specify that an entity will use a
generated primary key.
In VendorPart, the following code specifies the settings for generating primary key values:
@TableGenerator(
name=
"vendorPartGen",
table=
"EJB_ORDER_SEQUENCE_GENERATOR",
pkColumnName=
"GEN_KEY",
valueColumnName=
"GEN_VALUE",
pkColumnValue=
"VENDOR_PART_ID",
allocationSize=10)
@Id
@GeneratedValue(strategy=GenerationType.TABLE,
generator=
"vendorPartGen")
public Long getVendorPartNumber() {
return vendorPartNumber;
}
The @TableGenerator annotation is used in conjunction with @GeneratedValue's
strategy=TABLE
element. That is, the strategy used to generate the primary keys is use a table in
the database. @TableGenerator is used to configure the settings for the generator table. The
name element sets the name of the generator, which is vendorPartGen in VendorPart.
The EJB_ORDER_SEQUENCE_GENERATOR table, which has two columns GEN_KEY and GEN_VALUE,
will store the generated primary key values. This table could be used to generate other entity's
primary keys, so the pkColumnValue element is set to VENDOR_PART_ID to distinguish this
entity's generated primary keys from other entity's generated primary keys. The
allocationSize
element specifies the amount to increment when allocating primary key
values In this case, each VendorPart's primary key will increment by 10.
The primary key field vendorPartNumber is of type Long, as the generated primary key's field
must be an integral type.
Compound Primary Keys
A compound primary key is made up of multiple fields and follows the requirements described
in
"Primary Key Classes" on page 688
. To use a compound primary key, you must create a
wrapper class.
The order Application
The Java EE 5 Tutorial · September 2007
714