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.

An entity needs a database primary key even when its Java object has no identifier yet. With `GenerationType.IDENTITY`, the database supplies a numeric key through an auto-incremented primary key column when the row is inserted. Select it on the entity’s `@Id` field with `@GeneratedValue(strategy = GenerationType.IDENTITY)`. section 5.2.4

Persisting an entity

An `Item` can declare `@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;`. After `entityManager.persist(item)`, do not assume `item.getId()` is already non-null: an ORM may defer the INSERT, while an identity-column value becomes available only after that INSERT. section 5.2.4 section 5.2.5

Choose the generation strategy according to when the application needs the key:

  • `IDENTITY` uses an auto-incremented column and produces its value on INSERT. section 5.2.4
  • `SEQUENCE` obtains a value separately before INSERT. An enhanced-sequence generator is recommended when portable, pre-insert identifiers and optimization options matter. section 5.2.4 section 5.2.5
  • `TABLE` reads and updates an extra table before INSERT; `AUTO` delegates the choice to the configured database dialect. section 5.2.4

A database identifier is not the same as Java instance identity (`==`) or equality (`equals()`). Different Java objects can represent the same row, and a closed persistence context no longer guarantees identity mapping for detached instances. section 1.2.3 section 10.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Defines the JPA setting and explains insert-time identifier availability, without specifying vendor-specific identity-column DDL.
Examples
Uses an Item persisted through EntityManager and compares identity columns with sequences, tables, and dialect-selected generation.
What it assumes
Builds from Java identity and equality and SQL primary keys before addressing JPA entity identity.
What you can do after
Operate/configure it with `@GeneratedValue(strategy = GenerationType.IDENTITY)` and account for keys that become available only after INSERT.
How it connects
Connects primary keys and entity persistence to database identity, Java equality, persistence contexts, and identifier generation strategies.

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.