Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Entity Mapping

Identifiers and Generation Strategies

Choose primary keys in Hibernate: @Id, @GeneratedValue with IDENTITY, SEQUENCE, UUID, composite keys with @EmbeddedId, and why SEQUENCE enables JDBC batching.

Every entity needs an identifier, and the persistence context uses it as the key of its cache. How the identifier is generated affects performance more than most mapping choices: it decides whether Hibernate can batch INSERTs and when the id becomes known.

Real Hibernate code is read-only in this lesson; runnable programs are plain-Java stand-ins.

@Id and @GeneratedValue

Java
@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    ...
}

Without @GeneratedValue you assign the id yourself before persist. With it, Hibernate asks the strategy for a value.

Strategy How the id is made Notes
IDENTITY The database column auto-increments Id known only after the INSERT runs, so no INSERT batching
SEQUENCE A database sequence Ids can be fetched ahead in blocks; allows batching
UUID A random UUID generated in Java No round trip, but larger keys
AUTO Hibernate picks per database Usually a sequence when the database has them
TABLE A helper table Portable but slow; avoid

IDENTITY

Java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Simple and works everywhere (MySQL, SQL Server, PostgreSQL identity columns). The catch: Hibernate must execute the INSERT immediately on persist to learn the id, so it cannot delay and group INSERTs into a JDBC batch.

SEQUENCE and the pooled optimizer

Java
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_seq")
@SequenceGenerator(name = "book_seq", sequenceName = "book_seq", allocationSize = 50)
private Long id;

With allocationSize = 50, one SELECT nextval reserves 50 ids. Hibernate hands them out from memory (the pooled optimizer), so 50 persists cost one sequence call and the INSERTs can be batched. The sequence in the database must increment by the same size (50); a mismatch produces duplicate or skipped ids. Hibernate's schema generation creates it correctly.

UUID

Java
@Id
@GeneratedValue                // a UUID-typed id uses UUID generation
private UUID id;

UUIDs are unique across systems and can be created before the row exists, which helps with merging data or exposing ids publicly. Random (version 4) UUIDs scatter inserts across a B-tree index; time-ordered UUIDs (version 7) are friendlier to the database.

Composite keys

When a natural key has several columns, use an @Embeddable id class with @EmbeddedId:

Java
@Embeddable
public class EnrollmentId implements Serializable {
    private Long studentId;
    private Long courseId;
    // equals() and hashCode() are mandatory
}

@Entity
public class Enrollment {
    @EmbeddedId
    private EnrollmentId id;
    private LocalDate enrolledOn;
}

The id class must implement equals and hashCode over its fields, and should be Serializable.

equals and hashCode of entities

Hibernate needs a stable identity for entities stored in sets. Two safe approaches:

  • A natural key (for example the ISBN) compared in equals/hashCode.
  • The generated id, compared only when it is not null, with a constant hashCode (for example getClass().hashCode()).

Never use a mutable field that changes after the entity is stored, because its hash code would change while it sits in a HashSet.

Stand-in: why block allocation saves round trips

Java Stand-in: pooled sequence optimizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: IDENTITY vs a pre-assigned id with real JDBC

Java Stand-in: identity column and generated keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does GenerationType.IDENTITY prevent JDBC INSERT batching?

    Hibernate needs the generated id right away to place the entity in the persistence context.
  2. 2. What does allocationSize = 50 on a sequence generator do?

    The pooled optimizer fetches one value and hands out a block of ids from memory.
  3. 3. What must a composite id class do?

    Hibernate compares and hashes ids, so equals and hashCode over all key fields are mandatory.
  4. 4. Which is a downside of random UUID primary keys?

    Random UUIDs are 16 bytes and insert at random index positions.

Summary

  • Pick the strategy deliberately: SEQUENCE for batching, IDENTITY for simplicity, UUID for client-side ids.
  • A sequence generator's allocationSize must match the database sequence increment.
  • Composite keys use @EmbeddedId with an equals/hashCode-correct id class.
  • Base entity equality on a natural key or the id, never on mutable fields.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Types, Enums and Converters