liveBook · Manning

Identity

As explained in Java Persistence with Spring Data and Hibernate epub

GenerationType.IDENTITY is the JPA identifier-generation option that obtains the identifier generated by an identity or auto-increment column during insertion.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains annotation selection, schema expectations, insertion timing, and tradeoffs with pre-insert generators.
Examples
Compares AUTO, SEQUENCE, IDENTITY, and TABLE strategies and illustrates persisting an Item with a generated primary key.
What it assumes
Assumes understanding of Java identity and equality when mapping entities with database identity.
What you can do after
Apply IDENTITY via JPA annotations and evaluate whether post-insert identifier availability suits an entity mapping.
How it connects
Connects identifier generation to primary keys, database sequences, SQL INSERTs, and JDBC batching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.