Unit Testing Hibernate's Optimistic Locking (within Spring)
hibernate, spring, testing
Solution
It seems that it simply isn't an option to transfer all the fields from a DTO (including version) to a freshly loaded entity, try to save it, and get an exception in case the entity was modified while the DTO was being modified on the client.
The reason for that is that Hibernate simply doesn't care what you do to the version field, given that you're working in the same session. The value of the version field is remembered by the session.
A simple proof of that:
@Test (expected = StaleObjectStateException.class)
public void testOptimisticLocking() {
A a = getCurrentSession().load(A.class, 1);
getCurrentSession().evict(a); //comment this out and the test fails
a.setVersion(a.getVersion()-1);
getCurrentSession().saveOrUpdate(a);
getCurrentSession().flush();
fail("Optimistic locking does not work");
}
Thanks everyone for help anyway!
Problem
I'd like to write a unit test to verify that optimistic locking is properly set up (using Spring and Hibernate). I'd like to have the test class extend Spring's `AbstractTransactionalJUnit4SpringContextTests`. What I want to end up with is a method like this: ``` @Test (expected = StaleObjectStateException.class) public void testOptimisticLocking() { A a = getCurrentSession().load(A.class, 1); a.setVersion(a.getVersion()-1); getCurrentSession().saveOrUpdate(a); getCurrentSession().flush(); fail("Optimistic locking does not work"); } ``` This test fails. What do you recommend as a best practice? The reason I am trying to do this is that I want to transfer the `version` to the client (using a DTO). I want to prove that when the DTO is sent back to the server and merged with a freshly loaded entity, saving that entity will fail if it's been updated by somebody else in the meantime.