What is Generation Strategy?
- Hibernate framework can use different strategies to generate primary key values.
- JPA provides four strategies that generate primary keys programmatically or use database features.
- We can use @GenratedValue annotation to represent primary key attributes.
- The following are the primary key generation strategies.
- GenerationType.AUTO
- GenerationType.IDENTITY
- GenerationType.SEQUENCE
- GenerationType.TABLE
GenerationType.AUTO
-
- The GenerationType.AUTO is the default generation type and lets the persistence provider choose the generation strategy.
- If Hibernate is the persistence provider then it selects Generation Strategy based on a specific database vendor.
- Most of the database vendors use GenerationType.SEQUENCE.
GenerationType.IDENTITY
-
- This is the easiest generation strategy to generate primary keys.
- But this strategy completely depends on the AUTO_INCREMENTED column of the database table.
- It means the database vendor which supports AUTO_INCREMENT features can use this generation strategy.
GenerationType.SEQUENCE
-
- This is the most commonly used generation strategy for most database vendors.
- This strategy requires an extra select statement to fetch the value from the database sequence.
- This strategy is independent of an auto-incremented column of the database table.
- It means the primary key will be generated even if the database vendor does not provide an auto-increment feature.
GenerationType.TABLE
-
- The GenerationType.TABLE generates the sequence by storing and updating its current value in the database table.
- It keeps a separate table with primary key values.
- This generation strategy requires the use of pessimistic locks. In such case, the lock statement is executed to ensure that the same sequence value is not allocated for two concurrent transactions.
- Since this strategy uses pessimistic locks, It slows down the application performance.