Question:
Currently there are several options available for generating IDs automatically with Hibernate and JPA combined.
Example: @GeneratedValue(strategy = GenerationType.IDENTITY)
.
I am looking for documentation on how to choose the specific ID generation strategy that best suits each case.
1-) How are they different?
2-) Why is one chosen over the other?
3-) Do all the strategies work if we talk about databases such as Oracle, MySQL, PostgreSQL, ..?
Answer:
CAR
Indicates that the persistence provider should pick an appropriate strategy for the particular database.
Indicates that the persistence provider must choose the appropriate strategy for each particular database.
IDENTITY
Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
Indicates that the persistence provider should assign the primary key for Entities using an identification column in the database.
SEQUENCE
Indicates that the persistence provider must assign primary keys for the entity using a database sequence.
Indicates that the persistence provider should assign primary keys for the "Entity" using the database sequence
This sequential number is particular to some databases and what it does is create a new number that does not repeat itself and return it. The difference is that there is no transaction isolation, so multiple transactions cannot get the same value. More info about this.
TABLE
Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
Indicates that the persistence provider should assign primary keys for the entity using underlying tables to guarantee unique values.
A table that helps you keep control. More info.
The application you are going to use has a lot to do with it, but for me it was not necessary to use a strategy other than IDENTITY
when the values are autonumeric. In the end hibernate does a good job and the goal is to avoid relying on a DB technology, which is one of the characteristics why I work with Spring Boot. I don't need to worry in the development stage about whether there will be changes to the DB manager or things like that which is usually a headache.