Sub topic 4
Identifiers and Generation Strategies
This chapter assumes you can map a basic @Entity and know what a primary key is in SQL. It covers how JPA identifies each entity and how the key value gets assigned.
The identifier
Every entity needs exactly one identifier, marked with @Id. It maps to the table's primary key. The persistence provider uses it to tell entities apart, to look them up with findById, and to decide whether save should insert or update.
Use a wrapper type such as Long instead of long. A new entity has no id yet, and null is how Spring Data recognizes that. A primitive long defaults to 0, which Spring Data treats as a real value in some cases and not in others. Wrapper types avoid that ambiguity.
Generation strategies
@GeneratedValue tells JPA to produce the key for you. The strategy attribute selects how.
| Strategy | How the value is produced | Notes |
|---|---|---|
| `IDENTITY` | The database auto-increments a column | The insert runs immediately to get the id, so Hibernate cannot batch inserts |
| `SEQUENCE` | The id comes from a database sequence | Allows batching and pre-allocating ids. Not supported by MySQL before 8 or by some older databases |
| `TABLE` | A separate table stores the next value | Portable but slow. Rarely a good choice |
| `AUTO` | The provider chooses | The result depends on the dialect, so it can change between databases |
import jakarta.persistence.*;
@Entity
@Table(name = "authors")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
protected Author() {
}
public Author(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
}IDENTITY is a good default for PostgreSQL, MySQL and H2 when you do not need bulk inserts. The column must be declared as an identity or auto-increment column in your schema.
Using a sequence
For heavy write workloads, prefer SEQUENCE with an allocation size. Hibernate then fetches several ids in one call and hands them out in memory.
import jakarta.persistence.*;
@Entity
@Table(name = "invoices")
public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "invoice_seq")
@SequenceGenerator(name = "invoice_seq", sequenceName = "invoice_seq", allocationSize = 50)
private Long id;
protected Invoice() {
}
public Long getId() { return id; }
}The allocationSize must match the sequence's INCREMENT BY value in the database. If they differ, Hibernate can hand out duplicate ids or skip large ranges.
Common errors
- Setting an id on a generated entity. Calling
saveon a new entity whose id you set by hand makes Spring Data assume it exists. It runs aselectand may then throw an exception or insert unexpectedly. - Mismatched
allocationSize. See the warning above. - Changing the id after persisting. Hibernate does not allow it. Treat the id as immutable.
- Relying on
AUTO. Switching databases can silently change the strategy and the schema it expects.
If you assign ids yourself, such as UUIDs created in application code, omit @GeneratedValue. For UUIDs generated by Hibernate, use @GeneratedValue on a UUID field.
Exercise
Why does IDENTITY prevent Hibernate from batching inserts, and which strategy lets you batch them?
Show answer
With IDENTITY, the database creates the id during the insert, so Hibernate must run each insert immediately to learn the id. This stops it from grouping inserts. SEQUENCE lets Hibernate get ids ahead of time, so inserts can be deferred and batched.
Exercise
A sequence is created with INCREMENT BY 1, but the entity uses allocationSize = 50. What can go wrong?
Show answer
Hibernate assumes each sequence call reserves 50 ids and hands them out from memory. With an increment of 1, the next call returns a value inside the range already used, so duplicate ids and primary key violations can occur. The allocationSize and the sequence increment must match.