Skip to content

Hibernate: does not calculate version updates until flush #33191

@KyleAure

Description

@KyleAure

When using Hibernate as the Persistence provider for Jakarta Data the following data integrity errors can occur:

DataJPATestServlet.testSortByVersionFunction:
expected:
<[testSortByVersionFunction-Customer4, testSortByVersionFunction-Customer2, testSortByVersionFunction-Customer1, testSortByVersionFunction-Customer3]> 
but was:
<[testSortByVersionFunction-Customer4, testSortByVersionFunction-Customer3, testSortByVersionFunction-Customer2, testSortByVersionFunction-Customer1]> 

Reason: Hibernate does not calculate the new value of the version field (in this case an int) until the flush occurs. And, the flush doesn't occur until the transaction is committed even when flush mode is set to AUTO (default).

In this case the original entity was:

PurchaseOrder [id=e4bf17c1-9efe-491d-88f5-b0ef34ac9fcb, purchasedBy=testSortByVersionFunction-Customer1, purchasedOn=2025-10-22T10:31:14.774073-05:00, total=21.99, versionNum=0

and the updated entity that was returned from em.merge() was:

PurchaseOrder [id=e4bf17c1-9efe-491d-88f5-b0ef34ac9fcb, purchasedBy=testSortByVersionFunction-Customer1, purchasedOn=2025-10-22T10:31:14.774073-05:00, total=31.19, versionNum=0]

Documentation:

Tests:

  • I was unable to avoid this behavior by setting the flush mode to commit <property name="jakarta.persistence.query.flushMode" value="COMMIT"/>
  • I was unable to avoid this behavior by setting the LockModeType to PESSIMISTIC_FORCE_INCREMENT
  • I was unable to avoid this behavior by surrounding the update methods with tran.begin() and tran.commit().
    • It seems like hibernate just rejects all merges that are done on detached entities.

Resolution:

  • Will need to do some testing to see how we can merge detached versioned entities in Hibernate.
  • Will need to ensure that if multiple updates are happening in a single transaction that the version is only updated once.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions