GenerationType.IDENTITY maps an entity identifier to a database column that generates a numeric value on INSERT. The persistence provider obtains the generated identifier from the insertion. section 5.2.4 section 5.2.5
Map an auto-incremented identifier
Declare the identifier with @Id and select the strategy with @GeneratedValue: `@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;` Hibernate expects an auto-incremented primary-key column and creates one in the table DDL when its schema tools are used. section 5.2.4
The identifier is available only after the INSERT. An ORM may otherwise queue an insertion to optimize SQL execution, so code should not assume that a generated identifier is available before the row is inserted. section 5.2.5
Compare IDENTITY with the other standard JPA generation strategies:
- AUTO lets Hibernate choose a strategy for the configured database dialect. section 5.2.4
- SEQUENCE obtains a value from a database sequence before the INSERT. section 5.2.4
- TABLE reads and updates an extra table holding the next primary-key value before INSERTs. section 5.2.4
When identifiers must be available before INSERTs, prefer a pre-insert strategy. Hibernate’s enhanced-sequence uses a native sequence where supported and otherwise emulates one with a table; it also offers optimizers for large datasets. section 5.2.5
