Nov 8, 2018

Primary key generation in JPA

Using Identity Columns

When your database supports identity columns (such as MySQL, SQL Server database), you can configure JPA to use an identity column to generate identifiers.

The value of the primary key column will be automatically generated by the database.

Using sequences

Oracle Database and PostgreSQL use explicit sequence type to generate unique primary key numbers. You can use a specific named sequence object (whether it is generated by schema generation or already exists in the database). JPA implementation obtains the next value of the sequence and use it to insert a new row into the database table.

Using table

You can have a separate table which stores in a single row the sequence name along with the next number to use for the primary key. For performance reasons the next value is not increased by one, whenever JPA implementation needs a new value for the primary key but by a much higher number (e.g. 50). Once the range of values becomes reserved, JPA implementation can assign primary keys without accessing the database. When every value in the range becomes used, JPA implementation reserves a new range and the cycle continues.

Additionally, in such table we can have multiple rows with each row serving different entity. The only requirement is to use unique sequence names for each entity.

The table strategy is a complicated one but it is completely portable across different databases. If you are developing an application which can use multiple RDBMS or there may be a need to port to a new RDBMS in the future, using table strategy is a viable option.

Using a Default Generation Strategy

Specifying a strategy of AUTO allows JPA to select the strategy to use. For example, EclipseLink typically picks TABLE as the strategy, since it is the most portable strategy.

Using a Custom Strategy

You may choose to implement your own sequencing, such as UUID