Skip to content
Advertisement

HIbernate “StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1”

When an existing user makes a request the method first deletes the oldest record before saving the new request. The code below works fine IF the requests don’t come in too rapidly (using an Oracle DB).

JavaScript

Output:

JavaScript

However, if the user were to submit requests in a very quick fashion, i.e. happy clicker, the same code generates a StaleStateException error.

JavaScript

Seems like the code hasn’t had time to complete the change before the next one came in causing the code to try to delete the same record twice. Other than changing the front end or something else before this method, is there a way around this?

I’ve tried the @Transactional and @Lock options with no success. Spent a lot of time in this thread but the solutions either didn’t work or didn’t apply: Hibernate – Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

Advertisement

Answer

If users clicking rapidly is not expected, strongly recommend you to think of Debouncing API requests in front to skip back to back requests/events.

As you said rightly issues is happening because of inconsistency between what entities loaded to a individual session and current state of database.

This can be solved in multiple ways like using pessimistic locking with (select for update) comes with performance bottle necks, synchronizing the method …. etc

Simplest way to handle this is deleting using a JPA query and ordering at database level, so this always works on the current state of record table.

JavaScript

Please correct the above query according t your Entity design.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement