Quick revision
The short answer
A bulk JPQL update runs as one SQL statement and never goes through the entity lifecycle, so @PreUpdate callbacks and entity listeners, including Spring Data's auditing listener, do not run, and the @Version column is not incremented unless the statement does it. Sessions that loaded a product before the update still hold the old version, their later save matches it, and they overwrite the new price without an OptimisticLockException. We fix it by incrementing the version and setting audit columns in the bulk statement, or by processing entities in batches when callbacks must run.
What to remember
In this answer, we saw that a bulk JPQL update bypasses everything Hibernate does per entity: lifecycle callbacks, auditing listeners and the @Version increment. Because the version stayed the same, a session holding the old product passed the optimistic lock check and overwrote the new price. We fixed it by incrementing the version and setting audit columns inside the bulk statement, or by processing entities in batches when listeners must run.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A bulk JPQL update runs as one SQL statement and never goes through the entity lifecycle, so @PreUpdate callbacks and entity listeners, including Spring Data's auditing listener, do not run, and the @Version column is not incremented unless the statement does it. Sessions that loaded a product before the update still hold the old version, their later save matches it, and they overwrite the new price without an OptimisticLockException. We fix it by incrementing the version and setting audit columns in the bulk statement, or by processing entities in batches when callbacks must run.
Why this question is asked
This bug is nasty because nothing fails. The price change runs, returns a row count, and days later someone notices that some prices went back to their old values and that the audit columns say nobody touched the products. Interviewers ask it to see whether we know which JPA features live in the database and which live in Hibernate's handling of entities. In this answer, we will recap how optimistic locking and entity listeners work, reproduce the lost update, explain why the bulk update skipped both, and go through the fixes.
1A Quick Recap of Optimistic Locking and Entity Listeners
Optimistic locking protects against two users editing the same row at the same time without holding database locks. The entity has a field annotated with @Version. When Hibernate updates the entity, it adds where version = ? with the version it loaded, and sets the version to the next value. If another transaction changed the row in the meantime, the version no longer matches, zero rows are updated, and Hibernate throws an OptimisticLockException.
Entity listeners are methods that JPA calls at lifecycle events of an entity: @PrePersist before an insert, @PreUpdate before an update, and so on. Spring Data's AuditingEntityListener uses them to fill @LastModifiedDate and @LastModifiedBy. Hibernate Envers, which keeps a history table, hooks into similar events.
2Reproducing the Lost Update
An editor opens product 7 in the admin screen. Meanwhile a job raises all prices by 10 percent with a bulk update. Then the editor saves a change to the description.
4 messages in order. Play them, or step through them one at a time.
The bulk update changed the data but not the version, so the conflict is invisible.
Notice the where clause: the editor's save expects version 5, and the row still has version 5 because the bulk update did not touch it. So the check passes, and the full entity is written back with the old price. The 10 percent raise for product 7 is silently lost.
3Why the Bulk Update Skipped Versions and Listeners
Version checks, version increments and listener calls are not database features. They are things Hibernate does while it handles a managed entity: at flush, it sees the entity is dirty, calls @PreUpdate listeners, adds the version condition and increments the version.
A bulk JPQL update never has an entity in hand. Hibernate translates the statement to SQL and sends it, and the database changes thousands of rows that were never loaded into Java. There is no object to call a listener on and no per-row flush. So updatedAt stays at its old value, Envers records nothing, and version stays the same unless our statement changes it.
4Fix 1: Increment the Version and Set Audit Columns in the Statement
If the bulk update is the right tool, and for millions of rows it usually is, we make it do explicitly what the entity path would have done.
Now the editor's stale save finds version 6 in the row, updates zero rows, and Hibernate raises the exception, so the editor reloads and sees the new price. HQL also offers update versioned Product p set ..., which tells Hibernate to increment the version for us; it is Hibernate-specific, so check your version, and the explicit form is clearer to readers.
The audit columns must be set by hand too. If an audit history table is required, for example with Envers, a bulk statement will not feed it, and we either write the history rows ourselves in the same transaction or choose the next fix.
5Fix 2: Process Entities in Batches When Callbacks Matter
When per-row logic is essential, such as history, domain events or complex validation, we load and modify entities in pages, so listeners and versions work as normal. Each batch is its own short transaction, and we clear the persistence context after each one to keep memory flat.
- Must listeners, Envers or domain events run per row?YesLoad and update entities in batchesNoUse a bulk update
- Bulk: increment version in the statementp.version = p.version + 1
- Bulk: set audit columns in the statement
updatedAt,updatedBy - Clear the persistence context afterwards
clearAutomatically= true
4 steps in order. Play them, or step through them one at a time.
This is slower, maybe minutes instead of seconds for a million rows, but every change is versioned and audited exactly like an edit through the application. For a stable walk over a changing table, paging by id ranges (where id > :lastId order by id limit 500) is safer than offsets.
6Follow-up questions
Does a native SQL update behave the same way?
Yes, and it is even further from the entity model. Native updates bypass versions and listeners exactly like JPQL bulk updates, and in addition Hibernate cannot tell which entities changed, so by default it invalidates the whole second-level cache. The same fixes apply: set version and audit columns in the SQL.
Could a database trigger maintain the version and audit columns?
It can, and it then covers every writer, including other applications. The catch is that Hibernate also increments the version on entity updates, so the trigger must not double-increment, and audit user names are not known to the database unless we pass them, for example through a session variable. Many teams prefer explicit statements for clarity.
Why did the editor's save write the price at all?
By default Hibernate's update statement for an entity includes all columns, not just the changed ones, and merging a detached entity copies all its fields. So the old price in the editor's object was written back. @DynamicUpdate would limit the update to changed columns, which reduces the damage, but the real fix is a correct version.
7Conclusion
In this answer, we saw that a bulk JPQL update bypasses everything Hibernate does per entity: lifecycle callbacks, auditing listeners and the @Version increment. Because the version stayed the same, a session holding the old product passed the optimistic lock check and overwrote the new price. We fixed it by incrementing the version and setting audit columns inside the bulk statement, or by processing entities in batches when listeners must run.
Open with
The cause is that bulk JPQL updates skip the entity lifecycle. Optimistic locking, @PreUpdate callbacks and Spring Data's auditing listener are all things Hibernate does while it flushes a managed entity: it calls the listeners, adds where version equals the loaded version, and increments it.
Then, if they want more
A bulk update never loads the products. It is translated into one SQL update, so no listener runs, updatedAt stays old, and the version column is not changed unless the statement changes it. That breaks conflict detection.
An editor who loaded product 7 at version 5 before the price update still holds version 5, the row still has version 5, so the editor's save matches, updates one row, writes the old price back, and nobody gets an OptimisticLockException.
To fix it, I make the bulk statement do what the entity path would do: set p.version = p.version + 1 and the audit columns explicitly, or use Hibernate's update versioned. Then stale saves fail as they should.
If per-row callbacks really matter, for example Envers history or domain events, I process the products as entities in batches of a few hundred with short transactions, accepting that it is slower.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "After a bulk JPQL update of prices, optimistic locking stops detecting conflicting edits...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/e2fa84cfe0/