I have a page where I display all contacts. This is just the read only page and all I do is iterate through all contacts for some group and display them:
//Not lazy load of contacts, I cannot use lazy loading
List<Contact> contacts = someService.getContacts(groupId);
for (Contact contact : contacts) {
//add contact properties to the model to be displayed later
}
At the same time I might have a separate, background thread which updates one of the contacts. The thread updates a field that I'm not going to display, so I'm perfectly OK with data desynchronising in this case.
The problem is the Hibernate will update the contact's version number and commit it to my db (when the background thread finishes). So when my for loop hits such an object the following exception will be thrown.
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
Which is perfectly ok. Is there a way to disable object's version checking during iteration through a hibernate's collection? When I say disable, I mean in this particular scenario, in this particular for loop? But not other situations.
I think it happens because the underlying collection is the AbstractPersistentCollection and its iterator will check each member's version with corresponding db value.
You cannot disable optimistic locking on a session-basis, but there are some alternatives to handle this situation: