Up to now we have relied on the application to set an entity's primary key by supplying a primary key identifier as a parameter. However, we may want to relieve the application of this responsibility and use automatically generated keys. JPA provides the Table, Sequence, Auto, and Identity strategies for generating primary keys.
With this strategy the persistence engine uses a relational database table from which the keys are generated. This strategy has the advantage of portability; we can use it with any relational database. Here is an example of how we would specify a table generation strategy for the id
attribute of the Customer entity:
@TableGenerator(name="CUST_SEQ", table="SEQUENCE_TABLE", pkColumnName="SEQUENCE_NAME", valueColumnName="SEQUENCE_COUNT") @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="CUST_SEQ") public int getId() { return id; }
First we use the @TableGenerator
annotation to specify the table used for key generation...