Using Session.setReadOnly(false) seems to reset the state of an entity even if it was already in the session read/write.
In order to try to minimise dirty checking time during flushes, we experimented with a method that essentially did this:
Code:
Entity getEntity(Class clazz, int id, boolean readOnly)
{
// (Code to get session (via Spring HibernateTemplate) omitted)
session.get(clazz, id);
session.setReadOnly(readOnly);
}
We found that if we did this:
Code:
Entity entity = getEntity(clazz, id, false);
entity.setSomeProperty(someValue);
session.save(entity);
And then in some other part of the code (as part of the same transaction) this (for the same entity):
Code:
Entity entity = getEntity(clazz, id, false);
entity.setSomeProperty(someOtherValue);
session.save(entity);
The entity's property was not updated to someOtherValue.
Looking at org.hibernate.engine.EntityEntry.setReadOnly() it seams that the loaded state is reverted to that in the persister regardless of whether the state is currently already read/write.
Is this the correct behaviour? I could understand that going from read-only to read/write would overwrite any updates done while read-only.
It would be nice if there were some way to tell whether an entity was already in the session read/write. Then we could write a general purpose method to get an entity and set it read-only only if it's not already in the session read/write.