I want to increment a field in a database table by 1 using Hibernate.
I can do this by simply loading an object, incrementing the value and updating the object however if another thread comes along and updates the field in between the load and the update then the value will become corrupted.
So instead I have called an update directly on the database:
Query updateHits = createQuery(
"UPDATE Job SET hitCount = hitCount + 1 WHERE id = :jobId" );
updateHits.setInteger( "jobId", job.getId() );
updateHits.executeUpdate();
However my understanding is that this bypasses optimistic locking in the database and I am currently experiencing an issue with deadlocks in SQL server and I believe this is the culprit.
Is there a way to increment a field without calling the update directly and while maintaining data integrity?