Issue
I'm looking for clarification on this question: @GeneratedValue(strategy="IDENTITY") vs. @GeneratedValue(strategy="SEQUENCE") (nearly a decade old has anything changed?)
Getting started with learning jpa, the following generation types both seem to auto-increment the primary keys that get generated by 1.
Identity:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Sequence:
@Id
@SequenceGenerator(
name = "my_sequence",
sequenceName = "my_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "my_sequence"
)
private Long id;
I understand that the sequence object created by GenerationType.SEQUENCE
is not tied directly to a table in the way GenerationType.IDENTITY
is. The old question mentions that sequence can be more flexible. Are there any objective pros or cons to choosing one of these strategies over the other? Also anything new considering the age of the question being referenced?
Solution
As it's stated in the hibernate documentation:
It is important to realize that using
IDENTITY
columns imposes a runtime behavior where the entity row must be physically inserted prior to the identifier value being known.This can mess up extended persistence contexts (long conversations). Because of the runtime imposition/inconsistency, Hibernate suggests other forms of identifier value generation be used (e.g. SEQUENCE).
There is yet another important runtime impact of choosing IDENTITY generation: Hibernate will not be able to batch INSERT statements for the entities using the IDENTITY generation.
The importance of this depends on the application-specific use cases. If the application is not usually creating many new instances of a given entity type using the IDENTITY generator, then this limitation will be less important since batching would not have been very helpful anyway.
Answered By - SternK