What is the primary key generation strategy of Hibernate?
Hibernate primary key generation strategy is a method used to specify how to generate the primary key values of an entity. Hibernate provides several primary key generation strategies, with the following being commonly used:
- Auto-increment (GenerationType.IDENTITY): uses the database’s auto-increment field to generate primary key values, suitable for most databases such as MySQL, SQL Server, etc.
- Sequence (GenerationType.SEQUENCE): Utilizes the database’s sequence to generate primary key values, suitable for certain databases such as Oracle and PostgreSQL.
- Table (GenerationType.TABLE): Use a dedicated table to store the sequence of primary key values, suitable for all databases.
- UUID (GenerationType.UUID): Using UUID to generate primary keys ensures uniqueness.
- Custom (GenerationType.CUSTOM): Use a custom generation strategy to generate primary key values.
You can specify the primary key generation strategy by adding @GeneratedValue(strategy = GenerationType.XXX) annotation on the primary key in the entity class. Hibernate will generate the primary key value based on the specified strategy and save it to the database.