Sub topic 4
Identifiers and generation strategies
This chapter assumes you know how to map a class with @Entity and @Table, and that you understand primary keys in SQL. It covers how JPA identifies an entity, the four generation strategies, how the choice affects batching, and the mistakes that cause trouble in practice.
What an identifier does
Every entity needs an identifier. It maps to the table's primary key and marks the field with @Id. The persistence provider (Hibernate) uses it for three things:
- It is the key of the entity in the persistence context. Inside one session, a given row is represented by one object.
- It is the argument of
findandfindById. - Spring Data uses it to decide whether
save()should persist a new row or merge an existing one.
The identifier type must be a primitive wrapper, String, UUID, a date type, or an embedded composite key. Prefer wrapper types such as Long over long. A null value then means "not yet saved", while a primitive 0 is ambiguous.
Assigned identifiers
If you provide no @GeneratedValue, the application must set the identifier before saving. This suits natural keys, such as an ISBN or a country code, and identifiers created by another system.
import jakarta.persistence.*;
@Entity
@Table(name = "countries")
public class Country {
@Id
@Column(length = 2)
private String code;
@Column(nullable = false)
private String name;
protected Country() {
}
public Country(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() { return code; }
public String getName() { return name; }
}Assigned identifiers have a catch. When you call repository.save(country), Spring Data checks whether the entity is new. For a non-primitive id, it treats the entity as new when the id is null. Your Country always has an id, so Spring Data calls merge. Hibernate then runs a select first to see whether the row exists, and inserts only if it does not. You can avoid this by adding a @Version field, which Spring Data also uses to detect new entities, or by implementing Persistable<ID>.
Generated identifiers
@GeneratedValue asks the provider to produce the value. The strategy attribute selects how.
| Strategy | Source of the value | Insert timing | Batching |
|---|---|---|---|
| `IDENTITY` | Auto-increment column | Immediately on `persist` | Disabled for inserts |
| `SEQUENCE` | Database sequence | Deferred until flush | Supported |
| `TABLE` | Row in a helper table | Deferred until flush | Supported, but slow |
| `AUTO` | Provider chooses | Depends | Depends |
IDENTITY
The database assigns the value when the row is inserted.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;This is simple and works on MySQL, SQL Server, PostgreSQL and H2. The cost is that Hibernate cannot know the id until the insert runs. So persist must execute the insert at once, even inside a transaction, and Hibernate cannot group inserts into JDBC batches. For most CRUD applications this does not matter. For bulk loading it does.
SEQUENCE
The provider asks a database sequence for the next value, then uses it in the insert. Because the id is known early, inserts can be postponed and batched.
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_seq")
@SequenceGenerator(name = "book_seq", sequenceName = "book_seq", allocationSize = 50)
private Long id;allocationSize is the important setting. With a value of 50, Hibernate calls the sequence once, then hands out 50 ids from memory. This is the pooled optimizer. It cuts round trips, but the sequence's INCREMENT BY must equal allocationSize. If they differ, Hibernate may produce duplicate ids or large gaps. When you generate the schema with Hibernate, it sets this for you. When you write migrations by hand, you must match them yourself.
TABLE
The provider keeps counters in a table and updates them with row locks. It works on any database, but it is slow under concurrency. Use it only when the database has neither sequences nor identity columns.
AUTO
AUTO lets Hibernate choose. In Hibernate 6, on databases that support sequences, it picks SEQUENCE and uses a sequence named after the entity (for example book_seq) with an allocation size of 50. On other databases it falls back to identity or table. Because the result depends on the dialect and the Hibernate version, name your strategy explicitly in code that you plan to keep.
UUID
For a UUID field, Hibernate 6 can generate the value itself.
import jakarta.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "api_tokens")
public class ApiToken {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(nullable = false)
private String label;
protected ApiToken() {
}
public ApiToken(String label) {
this.label = label;
}
public UUID getId() { return id; }
public String getLabel() { return label; }
}GenerationType.UUID is part of JPA 3.1, which Spring Boot 3 uses. The value is generated in the application, so batching works and the id is known before the insert. The trade-off is that random UUIDs scatter inserts across a B-tree index, which hurts write performance on large tables. They are also 16 bytes against 8 for a bigint, and that extra size is copied into every foreign key and index that refers to them.
How the strategies compare in a flow
The diagram shows when the id becomes known, which decides whether inserts can be deferred.
Enabling insert batching
With SEQUENCE, you also need to switch batching on. It is not enabled by default.
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=trueorder_inserts sorts statements by entity type so that rows of one table are adjacent and can share a batch. Check the effect by enabling statement logging in a test, not by assuming it works.
Composite identifiers
When the key spans several columns, put them in an @Embeddable class and use @EmbeddedId. The key class must be Serializable and must implement equals and hashCode over all its fields.
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class EnrollmentId implements Serializable {
private Long studentId;
private Long courseId;
protected EnrollmentId() {
}
public EnrollmentId(Long studentId, Long courseId) {
this.studentId = studentId;
this.courseId = courseId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnrollmentId other)) return false;
return Objects.equals(studentId, other.studentId)
&& Objects.equals(courseId, other.courseId);
}
@Override
public int hashCode() {
return Objects.hash(studentId, courseId);
}
}@Entity
@Table(name = "enrollments")
public class Enrollment {
@EmbeddedId
private EnrollmentId id;
private int grade;
protected Enrollment() {
}
public Enrollment(EnrollmentId id, int grade) {
this.id = id;
this.grade = grade;
}
}Composite keys cannot use @GeneratedValue, so they behave as assigned identifiers, with the merge behavior described earlier.
Common errors
- Changing an id after persisting. Hibernate throws an exception such as "identifier of an instance was altered". Treat the id as immutable and provide no setter.
- Mismatched sequence increment. The sequence increments by 1 while
allocationSizeis 50. The result is duplicate key errors. Make the two values equal. - Expecting an id before commit with IDENTITY. The id is set right after
persist, but the row can still be rolled back. - Relying on
AUTOafter an upgrade. A Hibernate upgrade changed the default for many projects, and existing schemas stopped matching. Declare the strategy. - Using
longfor the id.save()cannot tell a new entity from one with id0, in the way it can fornull. Actually, for primitives Spring Data treats0as new, but the mapping loses the "unsaved" signal in other code. Use wrappers.
Choosing a strategy
- If you need bulk inserts and your database has sequences, use
SEQUENCEwith a matchingallocationSize. - If the database is MySQL or you insert rows one at a time,
IDENTITYis acceptable and simplest. - If ids must be created outside the database or exposed publicly without revealing counts, use
UUID, and consider a time-ordered variant if index locality matters. - If the business already has a stable unique key, an assigned id is fine, with
@VersionorPersistableto avoid the extraselect.
Exercise
A service inserts 10,000 Book rows in one transaction. The entity uses GenerationType.IDENTITY, and hibernate.jdbc.batch_size is set to 50. Hibernate still sends 10,000 separate insert statements. Why, and what change would allow batching?
Show answer
With IDENTITY, the database assigns the id only when the insert runs, so Hibernate must execute each insert immediately on persist and cannot group them. Batching is disabled for these inserts regardless of batchsize. Switching to GenerationType.SEQUENCE with a @SequenceGenerator whose allocationSize matches the sequence's INCREMENT BY (for example 50) lets Hibernate get ids in advance and defer the inserts to flush, where they are batched. Also set hibernate.orderinserts=true.
Exercise
You map Country with a String code assigned by the application and no @Version field. Every save() of a new country runs a select before the insert. Why does this happen, and how can you avoid it?
Show answer
The id is non-null, so Spring Data does not consider the entity new and calls merge, which first selects the row to see whether it exists. Avoid it by adding a @Version field (Spring Data then treats a null version as new) or by implementing Persistable<String> and returning true from isNew() until the entity is persisted.