# OptimisticLockException while flushing the hibernate session

**URL:** <https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345>\
**Category:** Hibernate ORM\
**Created:** [April 11, 2025, 5:38pm UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345 "2025-04-11T17:38:28Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yashwanth](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/yashwanth/32/3882_2.png) [@Yashwanth](https://discourse.hibernate.org/u/Yashwanth)\
**Post date:** [April 11, 2025, 5:38pm UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/1 "2025-04-11T17:38:28Z")

</div>

Hi,

We are currently using Hibernate 6.6.5 where we are facing a similar issue with a delete operation that throws an OptimisticLockException with the following stacktrace:

```auto
jakarta.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: delete from SLOTTOVIRTUALCONNREF where VIRTUALCONNECTOR_ID=? and SLOT_ID=?
	at org.hibernate.internal.ExceptionConverterImpl.wrapStaleStateException(ExceptionConverterImpl.java:221)
	at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:95)
	at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:167)
	at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:173)
	at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1433)
	at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1415)
	at chs.capitalmanager.pof.PersistenceSession.flushHibernateSession(PersistenceSession.java:374)

```

There are few bugs related to this same issue example: [HHH-19322](https://hibernate.atlassian.net/browse/HHH-19322), [HHH-13208](https://hibernate.atlassian.net/browse/HHH-13208)

We are unsure how the Hibernate release schedule works in our organization. We still use hbm.xml, which is deprecated but not removed in 6.6.5. If there is a fix for this issue, will there be a backport? Since we are still in our upgrading phase and cannot directly move to 7.0 (where hbm.xml is removed), any suggestions would be greatly appreciated.

---

<div class="post-metadata">

**Author:** ![beikov](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/beikov/32/258_2.png) [@beikov](https://discourse.hibernate.org/u/beikov)\
**Post date:** [April 14, 2025, 8:20am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/2 "2025-04-14T08:20:46Z")

</div>

Hibernate ORM 7.0 does not remove hbm.xml support yet, but ORM 8.0 will.

I don’t think your issue is related to the Jira tickets you posted. Please try to create a reproducer with our [test case template](https://github.com/hibernate/hibernate-test-case-templates/blob/master/orm/hibernate-orm-6/src/test/java/org/hibernate/bugs/JPAUnitTestCase.java) and if you are able to reproduce the issue, create a bug ticket in our [issue tracker](https://hibernate.atlassian.net) and attach that reproducer.

---

<div class="post-metadata">

**Author:** ![beikov](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/beikov/32/258_2.png) [@beikov](https://discourse.hibernate.org/u/beikov)\
**Post date:** [April 14, 2025, 9:10am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/3 "2025-04-14T09:10:41Z")

</div>

Slight correction, ORM 7.0 might actually remove hbm.xml support already: [HHH-19324 - Switch tests using hbm.xml to use mapping.xml by sebersole · Pull Request #9956 · hibernate/hibernate-orm · GitHub](https://github.com/hibernate/hibernate-orm/pull/9956)

---

<div class="post-metadata">

**Author:** ![Yashwanth](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/yashwanth/32/3882_2.png) [@Yashwanth](https://discourse.hibernate.org/u/Yashwanth)\
**Post date:** [April 21, 2025, 5:36am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/4 "2025-04-21T05:36:17Z")

</div>

Hi Christian,

We found this issue in our project, as there is a unit test getting failed with the above exception, but the same unit test is passing when using hibernate version 5.6.x for now. Even so, it’s unclear what’s happening in the backend and why hibernate 6.6.x is throwing this exception, or if we’ve messed up something on our end. Can you please help us understand this and advise on how to proceed?

---

<div class="post-metadata">

**Author:** ![Heiser923](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/heiser923/32/3980_2.png) [@Heiser923](https://discourse.hibernate.org/u/Heiser923)\
**Post date:** [April 21, 2025, 7:36am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/5 "2025-04-21T07:36:49Z")

</div>

We encountered similar error as well when upgrading to Hibernate 6.6.x that involves entity persistence after transaction rollbacks, though I am not sure if it is the same as with yours.

What happens is that an entity gets initially persisted and flushed, which generates its ID and version number, but then the transaction fails and rolls back. However, our system has a separate listener component that receives this entity as an argument and attempts to persist it again, unaware that the original transaction was rolled back, and the record does not get persisted in the DB at all.

This problem relates to a behavior change in Hibernate 6.6.x documented in their migration guide under ‘Merge versioned entity when row is deleted.’ The way Hibernate 6.6.x handles previously rolled back entities with version information has changed, causing our persistence operations to fail in this specific scenario.

Reference: [6.6 Migration Guide](https://docs.jboss.org/hibernate/orm/6.6/migration-guide/migration-guide.html)

---

<div class="post-metadata">

**Author:** ![Yashwanth](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/yashwanth/32/3882_2.png) [@Yashwanth](https://discourse.hibernate.org/u/Yashwanth)\
**Post date:** [April 21, 2025, 9:39am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/6 "2025-04-21T09:39:02Z")

</div>

We’ve identified a breaking change in batch processing between Hibernate 5.5 and 6.x, specifically regarding how expectations are verified during batch operations **org.hibernate.engine.jdbc.batch.internal.BatchImpl#checkRowCounts**.

**Key Difference:**

Hibernate 5.x:

```auto
this.getKey().getExpectation().verifyOutcome(rowCounts[i], ps, i, statementSQL);

```

Hibernate 6.x:

```auto
statementDetails.getExpectation().verifyOutcome(rowCounts[i], statementDetails.getStatement(), i, statementDetails.getSqlString());

```

The fundamental change is that in 5.x, the expectation was retrieved from our custom `BatchKey` implementation, while in 6.x, it’s now obtained from `statementDetails`.

**Our Setup:**

```auto
    
public class CHSDBBatchBuilder extends BatchBuilderImpl {
    @Override
    public Batch buildBatch(BatchKey batchKey, Integer explicitBatchSize,
                           Supplier<PreparedStatementGroup> statementGroupSupplier, 
                           JdbcCoordinator jdbcCoordinator) {
        BatchKey keyHolder = batchKey != null ? new CHSDBBatchKey(batchKey) : batchKey;
        return super.buildBatch(keyHolder, explicitBatchSize, statementGroupSupplier, jdbcCoordinator);
    }
}

```

Our custom `BatchKey` implementation, which worked fine in 5.x, is effectively being ignored in 6.x due to this architectural change.

**Question:** What’s the recommended approach to migrate custom `BatchKey` implementations to Hibernate 6.x? Is there an equivalent way to customize batch expectations in the new architecture?

---

<div class="post-metadata">

**Author:** ![mbladel](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/mbladel/32/2128_2.png) [@mbladel](https://discourse.hibernate.org/u/mbladel)\
**Post date:** [April 29, 2025, 2:23pm UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/7 "2025-04-29T14:23:32Z")

</div>

@Yashwanth no, there is no replacement for the deprecated `BatchKey#getExpectation` method, as it’s no longer used. Why did you need a custom `BatchKey` implementation that produced a different `Expectation` in the first place? Note that these are SPIs, so breaking changes between major versions are very much to be expected.

---

<div class="post-metadata">

**Author:** ![Yashwanth](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/yashwanth/32/3882_2.png) [@Yashwanth](https://discourse.hibernate.org/u/Yashwanth)\
**Post date:** [April 30, 2025, 4:19am UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/8 "2025-04-30T04:19:06Z")

</div>

Hi @mbladel,

Let me explain our project’s cascade delete situation:

1. We extensively use cascade delete operations
2. During a delete operation, the expectation is a row count
3. However, when cascade delete removes foreign keys behind Hibernate’s back, it creates a row count mismatch
4. This mismatch triggers StaleStateException
5. To handle this, we created a custom BatchKey expectation and ignored the StaleStateException

This is the primary reason we implemented the Custom Batch Key in our project.

---

<div class="post-metadata">

**Author:** ![beikov](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/beikov/32/258_2.png) [@beikov](https://discourse.hibernate.org/u/beikov)\
**Post date:** [May 20, 2025, 4:02pm UTC](https://discourse.hibernate.org/t/optimisticlockexception-while-flushing-the-hibernate-session/11345/9 "2025-05-20T16:02:43Z")

</div>

I guess what you are looking for is roughly this feature request: [Jira](https://hibernate.atlassian.net/browse/HHH-17137)
