Video in progress
How do the IDENTITY, SEQUENCE and UUID strategies in @GeneratedValue differ?
With IDENTITY the database's auto-increment column provides the id. With SEQUENCE Hibernate takes values from a separate sequence and can reserve them in advance. With UUID the application itself generates the id. On PostgreSQL, SEQUENCE is usually the best choice.
📖 Answer
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
private Long id;
The practical difference:
| Strategy | When the id is known | Batch insert |
|---|---|---|
IDENTITY |
only after the INSERT runs | doesn't work |
SEQUENCE |
before the INSERT | works |
UUID (Hibernate 6.2+ GenerationType.UUID) |
immediately, in Java | works |
With IDENTITY, Hibernate sends the INSERT as soon as you call persist(), because it has no other way to learn the id. MySQL has no sequences, so IDENTITY is often used there.
allocationSize = 50 means Hibernate takes one value from the sequence and then hands out the next 50 ids from memory. That means fewer trips to the database. But the sequence's INCREMENT BY must also be 50, otherwise ids collide or Hibernate throws an error.
If you leave AUTO, Hibernate picks a strategy based on the dialect. The result can be unexpected, so I usually spell it out.
Sign up to mark studied questions and save your progress.