Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In a Spring Boot 3 JPA entity using Hibernate 6, write the id mapping for (a) a PostgreSQL sequence with batched inserts and (b) a UUID generated by the application. Why does GenerationType.IDENTITY hurt batching?

For a sequence we use @GeneratedValue(strategy = GenerationType.SEQUENCE) with a @SequenceGenerator whose allocationSize matches the sequence's INCREMENT BY, for example 50, so Hibernate can hand out 50 ids per database call. For an application-generated UUID we use GenerationType.UUID or Hibernate's @UuidGenerator. IDENTITY hurts batching because Hibernate only learns the id after each INSERT runs, so it must execute every insert immediately instead of grouping them.

Why this question is asked

Saving a thousand entities in a loop can take one round trip or a thousand, depending on two annotations on the id field. This is one of the most common performance surprises in Spring Data JPA projects, and interviewers use it to check whether we understand when Hibernate talks to the database. In this answer, we will recap what JDBC batching is, write the sequence mapping and the matching database sequence, write the UUID mapping, see why IDENTITY disables batching, and look at what goes wrong when the allocation size and the sequence disagree.

1A Quick Recap of JDBC Batching

Without batching, every INSERT is a separate round trip: Java sends the statement, the database runs it and replies. With batching, the JDBC driver collects many executions of the same prepared statement and sends them together. Inserting 1,000 rows then takes 20 round trips of 50 rows instead of 1,000, which can easily make a bulk save five to ten times faster.

Hibernate supports this, but only when it can delay inserts until flush time. To delay an insert, Hibernate must already know the entity's id, because the id is what it uses to track the entity in the persistence context, the first-level cache of managed objects.

2Mapping a PostgreSQL Sequence With Batched Inserts

Here is the mapping for an Order entity in Spring Boot 3 with Hibernate 6, using jakarta.persistence annotations.

Java
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
private Long id;
private String customerRef;
// getters, setters
}
-- Flyway migration: the increment must equal allocationSize
CREATE SEQUENCE order_seq START WITH 1 INCREMENT BY 50;

With allocationSize = 50, Hibernate uses its pooled optimizer. When it needs an id, it calls nextval('order_seq') once, gets for example 51, and knows that it may use the block of 50 ids ending at that value without asking again. Saving 1,000 orders then costs 20 sequence calls, not 1,000. The reason the sequence must INCREMENT BY 50 is that the next nextval must jump past the whole block, or a second application instance would be given ids from the same block.

Then we switch batching on. Spring Boot passes properties under spring.jpa.properties straight to Hibernate.

3Turning Batching On and Proving It

Two properties matter. batch_size sets how many statements go in one batch, and order_inserts sorts pending inserts by entity type, so that saving orders and order lines in alternation still forms long batches instead of breaking the batch at every switch.

Java
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.generate_statistics=true # only while measuring
// in a @Transactional service
for (int i = 0; i < 1000; i++) {
em.persist(new Order("C-" + i)); // no SQL yet, ids come from the pooled block
}
em.flush(); // 20 JDBC batches of 50 inserts
// statistics log: 20 JDBC batches executed, 20 sequence calls

Notice that persist() sends nothing to the database in this loop except the occasional sequence call. The inserts wait until flush, and then go out in groups of 50. For very large loads we also call flush() and clear() every few thousand entities, so the persistence context does not grow without limit.

4Generating a UUID in the Application

With a UUID, the id is created in Java before the insert, so batching works with no sequence at all. Jakarta Persistence 3.1 added GenerationType.UUID, and Hibernate 6.2 and later also offer @UuidGenerator, which lets us choose a style.

Java
@Entity
public class Payment {
@Id
@GeneratedValue(strategy = GenerationType.UUID) // random version 4 by default
private UUID id;
}
@Entity
public class Shipment {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME) // time-based; check your Hibernate version
private UUID id; // for which time-based versions it supports
}

The column is the native uuid type in PostgreSQL. A time-based style gives roughly ordered values, which keeps the primary key index tidy, as we discussed for UUIDv7; newer Hibernate versions add a version 7 style, so check your version. Some teams instead assign the id in the constructor with a UUIDv7 library, which also makes the id available before the entity is saved.

5Why IDENTITY Turns Batching Off

With GenerationType.IDENTITY, the database assigns the id while it executes the INSERT, from an identity column or auto-increment. Hibernate cannot know the id in advance. Because persist() must return with the entity managed and its id set, Hibernate executes the INSERT right away inside persist() and reads the generated key back. Each insert is sent alone, and Hibernate disables insert batching for that entity.

Java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // id bigint GENERATED ALWAYS AS IDENTITY
private Long id;
for (int i = 0; i < 1000; i++) {
em.persist(new Order("C-" + i)); // INSERT runs here, one round trip each
}
// statistics log: 0 JDBC batches, 1000 statements
Step throughpersist() with SEQUENCE versus IDENTITY
ServiceHibernatePostgreSQL
persist(order) with SEQUENCE
take next id from the pooled block
flush()
one batch of 50 INSERTs
50 row counts
persist(order) with IDENTITY
INSERT ... RETURNING id, right away
generated id

8 messages in order. Play them, or step through them one at a time.

6When allocationSize and INCREMENT BY Disagree

Suppose the annotation says allocationSize = 50 but the sequence was created with INCREMENT BY 1, which is the default. Hibernate calls nextval and gets 1, then 2 for the next block. It believes the first block covers ids up to 1 and the next one covers ids up to 2, but those blocks overlap the ones another instance or a later restart will compute. Two instances end up assigning the same ids, and inserts fail with a duplicate key violation on the primary key. The opposite mismatch, INCREMENT BY 50 with allocationSize = 1, does not collide but wastes 49 of every 50 numbers.

Recent Hibernate versions compare the two at startup when they can read the sequence metadata and can fail fast; check your version's increment size mismatch setting. The safest habit is to create the sequence in the same migration as the entity and write the two numbers side by side.

7Follow-up questions

Is a gap in sequence ids a problem?

No. Ids from a pooled block that were never used, for example because an instance restarted, are simply lost, and rolled back transactions also consume sequence values. Primary keys only need to be unique. If the business needs gapless numbers, such as invoice numbers in some countries, those must come from a separate counter row updated in the transaction.

Does Spring Data's saveAll() batch by itself?

saveAll() calls save() for each entity, and for a new entity save() calls persist(). So it batches only when the id strategy allows it and the batch properties are set. Note also that if the entity has an assigned id, such as a UUID set in the constructor, save() may call merge() instead, which first runs a SELECT; implementing Persistable with an isNew() method avoids that.

What about MySQL, which has no sequences?

MySQL's usual choice is AUTO_INCREMENT, which is IDENTITY in JPA, so inserts are not batched by Hibernate. Teams either accept it, use the table generator, which is slow, or generate UUIDv7 in the application so batching works.

8Conclusion

In this answer, we saw that a SEQUENCE mapping with a @SequenceGenerator whose allocationSize matches the sequence's INCREMENT BY lets Hibernate assign ids in blocks and batch inserts, once hibernate.jdbc.batch_size and order_inserts are set. An application-generated UUID through GenerationType.UUID or @UuidGenerator batches too. IDENTITY forces Hibernate to run each INSERT immediately to learn the id, which disables batching, and a mismatched allocation size causes duplicate keys or wasted ranges.

What to say in the interviewAbout 80 seconds aloud

Open with

For the sequence I would annotate the id with @GeneratedValue using GenerationType.SEQUENCE and a generator called order_seq, and add a @SequenceGenerator with sequenceName order_seq and allocationSize 50. In the Flyway migration I create the sequence with INCREMENT BY 50, because Hibernate's pooled optimizer takes one nextval and uses the 50 ids up to it, so the database must jump by the same amount or two instances would get overlapping blocks and hit duplicate key errors.

Then, if they want more

Then I set spring.jpa.properties.hibernate.jdbc.batch_size to 50 and order_inserts to true, so a thousand persists become twenty batches at flush time. For a UUID I use GenerationType.UUID from Jakarta Persistence 3.1, or Hibernate's @UuidGenerator from 6.2, with a time-based style if I want ordered keys, mapped to the native uuid column.

Both work with batching because the id exists before the insert. IDENTITY is different: the database assigns the id during the INSERT, and since persist must leave the entity with an id, Hibernate executes each insert immediately and reads the key back.

That means one round trip per row and no insert batching, which is why I avoid IDENTITY for tables with bulk inserts.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6, Spring Boot 3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In a Spring Boot 3 JPA entity using Hibernate 6, write the id mapping for (a) a...": https://scrivio-interview-library.netlify.app/databases/data-modeling/2184c62e39/