Skip to main content

Hibernate 8 Graph-Based Flush Ordering: What Changes for Inserts, Updates and Deletes (8.0.0.CR2)

Hibernate ORM 8.0.0.CR2 (release candidate) replaces the legacy action queue with a graph-based flush planner. Same Java run under hibernate.flush.queue.type=legacy and graph, with the real JDBC SQL captured: insert and delete order, unique-constraint failures that disappear, a NOT NULL case that is not rescued, batching, and how to switch back.

Hibernate does not run your persist(), remove() and field changes the moment you make them. It queues them and sends the SQL at flush time, and the order of that SQL decides whether a foreign key or a unique constraint complains. Hibernate ORM 8 replaces the queue that decides that order. This post runs the old queue and the new one side by side on the same code, prints the SQL each one really sent, and shows what got fixed, what did not, and how to switch back.
Versions tested (pre-release). Hibernate ORM 8.0.0.CR2, a release candidate published 24 Nov 2026 — not a Final release. Maven Central lists 8.0.0.Alpha1, Beta1–Beta4, CR1 and CR2 and no 8.0.0.Final, and the release page still calls 7.4 the latest stable series and warns that new 8.0 features may change in backward-incompatible ways. Jakarta Persistence 4.0.0-M8 (a milestone, resolved transitively), H2 2.5.252, JDK Temurin 25.0.5.1, Maven 3.9.11. Treat every behaviour below as CR2 behaviour: it may change before Final.

Why the order of SQL matters at all

Say you save an author and then a post that points at that author. The post table has a foreign key to author, so the author row has to exist before the post row. If you remove them, the post has to go first. The database enforces this; Hibernate has to produce SQL in a workable order. Unique constraints add a second rule: two rows may not hold the same email at the same moment, even if your final state is fine. Until 7.x, Hibernate used a queue with fixed buckets. Reading the jar (scripts/inspect-settings.sh) shows the legacy queue’s execution order is a hard-coded list of action types:
OrphanCollectionRemoveAction;
OrphanRemovalAction;
EntityInsertAction;
EntityUpdateAction;
QueuedOperationCollectionAction;
CollectionRemoveAction;
CollectionUpdateAction;
CollectionRecreateAction;
EntityDeleteAction;
Inserts, then updates, then collection work, then deletes, and inside each bucket the order you called things. That is cheap and usually enough, but it knows nothing about your constraints. Hibernate 8 adds a second queue that does. The 8.0 what’s new page describes it as planning the work from the mapped relational constraints, and the migration guide warns it “can often lead to different SQL or SQL being performed in different order”. Both pages also say it is the default.
Legacy queue: fixed buckets 1. all inserts 2. all updates 3. collection work 4. all deletes Inside a bucket, rows run in the order your code touched them. Graph queue: arrows from the mapping insert author insert post update post.author_id delete post delete author An arrow means: this row must run first. Rows with no arrow between them can share a batch. The legacy queue decides by statement type; the graph queue decides by constraints.
The picture is the whole idea. Legacy sorts by what kind of statement it is. Graph builds a small dependency graph per flush — an arrow wherever a foreign key or unique key means one row must go before another — and runs rows in an order that respects the arrows. Rows with no arrow between them are free to be grouped into the same batch, which matters in the batching section below.
How I checked this. The setting names and the two queue types in this post come from running javap on the CR2 jar, not from blog prose. Every SQL block below was captured from a real run by the test class FlushOrderingTest.java, which asserts the same facts, so a claim that stops being true fails the build. The captured text is pasted verbatim; regenerate it with scripts/run-all.sh.

Inserts: the parent finally goes first

The smallest experiment: build a post, point it at an author that has not been saved yet, and call persist on the post before the author. Run it once per queue.
Consumer<jakarta.persistence.EntityManager> work = em -> {
    Author a = new Author(1L, "Ada");
    em.persist(new Post(10L, "Hello", a));   // child persisted first, parent second
    em.persist(a);
};
The entities are tiny: Author and Post (a plain nullable @ManyToOne). The test lives in FlushOrderingTest.java (insertOrder). Real output:
legacy -> committed (3 statements)
  insert into post (author_id,title,id) values (?,?,?)  [null, Hello, 10]
  insert into author (name,id) values (?,?)  [Ada, 1]
  update post set author_id=?,title=? where id=?  [1, Hello, 10]

graph -> committed (3 statements)
  insert into author (name,id) values (?,?)  [Ada, 1]
  -- executeBatch()
  insert into post (author_id,title,id) values (?,?,?)  [null, Hello, 10]
  -- executeBatch()
  update post set author_id=?,title=? where id=?  [1, Hello, 10]
  -- executeBatch()

no setting at all -> committed (3 statements)
  insert into author (name,id) values (?,?)  [Ada, 1]
  -- executeBatch()
  insert into post (author_id,title,id) values (?,?,?)  [null, Hello, 10]
  -- executeBatch()
  update post set author_id=?,title=? where id=?  [1, Hello, 10]
  -- executeBatch()
Two things to read here. First, the order flipped: legacy sent insert into post first, graph sent insert into author first. Second, both queues still insert the post with a null author and fix it with an update afterwards. Graph put the parent first but did not remove that extra UPDATE in this scenario. The third block, run with no hibernate.flush.queue.type at all, is identical to the graph block, which confirms the default is graph.
Do not read this as “legacy was broken”. Legacy worked here because Hibernate nulls out a reference to an unsaved entity, inserts, and patches the column later. That is why the legacy run commits. What changed is the SQL you will see in your logs, and that is the sort of difference that breaks tests which assert on exact statement order.

Deletes: the child goes first

Same idea in reverse: load an author and one of its posts, remove the author first and the post second.
Consumer<jakarta.persistence.EntityManager> work = em -> {
    em.remove(em.find(Author.class, 1L));    // parent removed first
    em.remove(em.find(Post.class, 10L));
};
Test method deleteOrder in FlushOrderingTest.java. Output:
legacy -> committed (3 statements)
  update post set author_id=?,title=? where id=?  [null, Hello, 10]
  delete from author where id=?  [1]
  delete from post where id=?  [10]

graph -> committed (3 statements)
  update post set author_id=?,title=? where id=?  [null, Hello, 10]
  -- executeBatch()
  delete from post where id=?  [10]
  -- executeBatch()
  delete from author where id=?  [1]
  -- executeBatch()
Legacy deleted the author before the post. It committed anyway, because Hibernate first issued update post set author_id=null for the post that pointed at the removed author, so no row referenced the author when it was deleted. Graph issued the same update and then deleted post then author. Again the order differs, the end state is the same, and the extra update is still there.

Where it really fixes things: unique constraints

Foreign keys were forgiving in the runs above. Unique keys bite harder, because the offending value is real data, not a reference Hibernate can null out for you. The Account entity has @Column(unique = true) on email. Delete a row and insert a new row with the same email in one transaction. Test uniqueDeleteThenReinsert:
legacy -> FAILED (1 statement)
  insert into account (email,id) values (?,?)  [[email protected], 2]
  org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.CONSTRAINT_E INDEX PUBLIC.CONSTRAINT_INDEX_E ON PUBLIC.ACCOUNT(EMAIL NULLS FIRST) VALUES ( /* 1 */ '[email protected]' )"

graph -> committed (2 statements)
  delete from account where id=?  [1]
  -- executeBatch()
  insert into account (email,id) values (?,?)  [[email protected], 2]
  -- executeBatch()
Legacy runs inserts before deletes, so the new row collides with the row that was about to be deleted: a unique-index violation, rolled back. Graph sees that the delete must free the value before the insert uses it and sends delete then insert. Same Java, same database, one succeeds. This is the clearest real fix I found. Swap two unique values. Test uniqueSwap: row 1 gets row 2’s email and vice versa.
Consumer<jakarta.persistence.EntityManager> work = em -> {
    em.find(Account.class, 1L).email = "[email protected]";
    em.find(Account.class, 2L).email = "[email protected]";
};
Swap two unique emails in one flush row 1: [email protected] to [email protected]row 2 still holds b: collision row 2: [email protected] to [email protected]row 1 still holds a: collision Each update waits for the other: a cycle. The legacy queue runs row 1 first and fails. 1. row 2 to null 2. row 1 to b 3. row 2 to a Graph: break the cycle with a null.
Whichever update runs first collides with the other row, so no ordering of the two updates alone can work — it is a cycle. Real output:
legacy -> FAILED (2 statements)
  update account set email=? where id=?  [[email protected], 1]
  update account set email=? where id=?  [[email protected], 1]
  org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.CONSTRAINT_E INDEX PUBLIC.CONSTRAINT_INDEX_E ON PUBLIC.ACCOUNT(EMAIL NULLS FIRST) VALUES ( /* 2 */ '[email protected]' )"

graph -> committed (3 statements)
  update account set email=? where id=?  [null, 2]
  update account set email=? where id=?  [[email protected], 1]
  -- executeBatch()
  update account set email=? where id=?  [[email protected], 2]
  -- executeBatch()

graph with hibernate.flush.plan.uniquekey.order=false -> FAILED (2 statements)
  update account set email=? where id=?  [[email protected], 1]
  update account set email=? where id=?  [[email protected], 2]
  -- executeBatch()
  org.h2.jdbc.JdbcBatchUpdateException: Unique index or primary key violation: "PUBLIC.CONSTRAINT_E INDEX PUBLIC.CONSTRAINT_INDEX_E ON PUBLIC.ACCOUNT(EMAIL NULLS FIRST) VALUES ( /* 2 */ '[email protected]' )"
Legacy fails on the first update. Graph breaks the cycle itself: it sets row 2’s email to null first, then writes [email protected] to row 1, then [email protected] to row 2. That works only because the column is nullable — keep that in mind for NOT NULL unique columns, which I did not test. The third block turns off hibernate.flush.plan.uniquekey.order; the graph queue then fails exactly like legacy, which shows that setting is what produces the fix.
An oddity in the legacy failure. The legacy block shows the failing update twice. My JDBC recorder saw two executeUpdate calls for it, from two different lines of AbstractMutationExecutor.performNonBatchedMutation in the stack. I did not dig into why Hibernate issues it twice on that error path, so I am reporting what the recorder saw rather than explaining it.

What the graph does not rescue

The ordering change only helps when there is a valid order. A NOT NULL foreign key pointing at an entity that is never saved before the flush has none. Comment declares @JoinColumn(nullable = false); test notNullForeignKeyIsNotRescued persists a comment before its author:
legacy: java.lang.IllegalStateException
  org.hibernate.TransientPropertyValueException: Instance of 'com.ankurm.flush.Comment' references an unsaved transient instance of 'com.ankurm.flush.Author' (persist the transient instance) [com.ankurm.flush.Comment.author -> com.ankurm.flush.Author]
graph: java.lang.IllegalStateException
  org.hibernate.TransientPropertyValueException: Instance of 'com.ankurm.flush.Comment' references an unsaved transient instance of 'com.ankurm.flush.Author' (persist the transient instance before flushing) [com.ankurm.flush.Comment.author -> com.ankurm.flush.Author]
Both queues throw TransientPropertyValueException. Only the message text differs (the graph run says “before flushing”). If your code builds children before parents and relied on a nullable FK being patched up, graph will reorder it for you; if the FK is not null, the fix is still to persist the parent first.

Batching: fewer, bigger JDBC batches

Ordering also changes how well JDBC batching works. Persist two authors, each with a post, interleaved, with hibernate.jdbc.batch_size=10. The transcript marks each executeBatch():
legacy with hibernate.jdbc.batch_size=10 (4 statements)
  insert into author (name,id) values (?,?)  [A1, 1]
  -- executeBatch()
  insert into post (author_id,title,id) values (?,?,?)  [1, P1, 11]
  -- executeBatch()
  insert into author (name,id) values (?,?)  [A2, 2]
  -- executeBatch()
  insert into post (author_id,title,id) values (?,?,?)  [2, P2, 12]
  -- executeBatch()

graph with hibernate.jdbc.batch_size=10 (4 statements)
  insert into author (name,id) values (?,?)  [A1, 1]
  insert into author (name,id) values (?,?)  [A2, 2]
  -- executeBatch()
  insert into post (author_id,title,id) values (?,?,?)  [1, P1, 11]
  insert into post (author_id,title,id) values (?,?,?)  [2, P2, 12]
  -- executeBatch()
Legacy alternated author, post, author, post and flushed four one-row batches. Graph put both authors together and both posts together: two batches. The statements are the same; the grouping is not. In the legacy queue you usually had to turn on hibernate.order_inserts to get this (see the Hibernate 7 batch insert post); I did not test that combination here, so I am not claiming graph equals it.

Switching modes and the other settings

One property picks the queue. In the repo it is set in Lab.java:
if (queueType != null) {
    cfg.property("hibernate.flush.queue.type", queueType);
}
With no value, you get graph. hibernate.flush.queue.type=legacy restores the old queue, and the migration guide says it is available only temporarily. Test settingValues tried three values:
hibernate.flush.queue.type=GRAPH -> SessionFactory built
hibernate.flush.queue.type=Legacy -> SessionFactory built
hibernate.flush.queue.type=bogus -> java.lang.IllegalArgumentException: Unknown ActionQueue implementation: bogus. Valid values are 'graph' and 'legacy'.
Matching is case-insensitive and anything else fails fast at startup, listing the two valid values. The same property works in persistence.xml, hibernate.properties or Spring’s spring.jpa.properties.*, but I only ran the programmatic form.
Reference: all six settings, straight from the jar The constants in org.hibernate.cfg.FlushSettings, printed by scripts/inspect-settings.sh:
FLUSH_QUEUE_TYPE = "hibernate.flush.queue.type";
ORDER_BY_FOREIGN_KEY = "hibernate.flush.plan.foreignkey.order";
ORDER_BY_UNIQUE_KEY = "hibernate.flush.plan.uniquekey.order";
DEFERRABLE_EDGES_IGNORE = "hibernate.flush.plan.deferrable.ignore_edges";
DEFERRABLE_AVOID_BREAK = "hibernate.flush.plan.deferrable.avoid_break";
GRAPH_DEFER_IDENTITY_INSERTS = "hibernate.flush.queue.graph.defer_identity_inserts";
The defaults and meanings below come from the CR2 Javadoc. I ran two of them (the queue type, and the unique-key switch in the swap test); the others I have not exercised, so treat them as documented, not verified.
SettingDefaultWhat the Javadoc says
hibernate.flush.queue.typegraphgraph or legacy (verified)
hibernate.flush.plan.foreignkey.ordertrueorder operations by foreign key (not exercised)
hibernate.flush.plan.uniquekey.ordertrueorder by unique key (verified: false reproduces the legacy swap failure)
hibernate.flush.plan.deferrable.ignore_edgestrueassume deferrable constraints are checked at commit and add no edge (not exercised)
hibernate.flush.plan.deferrable.avoid_breaktruebreak deferrable constraints only as a last resort when resolving cycles (not exercised)
hibernate.flush.queue.graph.defer_identity_insertsfalsewhen false, non-delayed IDENTITY inserts still run immediately so ids are visible after persist (not exercised; my entities use assigned ids)
Reference: what is inside the jar The migration guide says org.hibernate.engine.spi.ActionQueue was renamed ActionQueueLegacy and the new queue interface lives in org.hibernate.action.queue.spi. Unzipping the CR2 jar agrees: ActionQueueLegacy and its OrderedActions enum are in engine.spi, while action.queue holds spi and internal packages including FlushCoordinator and GraphBasedActionQueue, and sub-packages named graph, cyclebreak, constraint and decompose. The queue type enum has exactly GRAPH and LEGACY, and the unique-cycle strategy enum has FAIL and IGNORE_UNIQUE_EDGES_IN_CYCLES. I did not read the planner source, so how it picks which edge to cut in a cycle is outside what I verified; the swap test shows one real outcome only. Code that implements or calls the old ActionQueue class directly (custom integrations, some extensions) will need attention; the guide lists that as an SPI change.

Should you switch, wait, or pin legacy?

My honest take. Do not move production to 8.0.0.CR2; it is a release candidate and the project says features may change incompatibly before Final. Do try it on a branch. The tests worth running first are the ones that assert exact SQL or statement counts, because the order will differ, and any code that works around unique-constraint ordering (extra flush() calls between a delete and an insert) — those workarounds may now be unnecessary. Setting hibernate.flush.queue.type=legacy is a reasonable stop-gap on 8.x, but it is documented as temporary, so use it to buy time, not as a destination. What I did not test: IDENTITY ids, collections and @OneToMany orphan removal, inheritance and secondary tables, deferrable constraints, other databases, and performance.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.