views:

22

answers:

1

Hi!,

I'm using Hibernate 3.5.5.Final and JPA2

How can make a testcase to test if the hibernate lock is working?

I wrote this, but seems that the test not pass in the current hibernate version (works fine in the previous version)

@Test(expected=OptimisticLockException.class)
public void testLock() {
    EntityManager em = getEntityManager();
    Foo foo1 = fooDAO.findById(1);
    em.lock(foo1, LockModeType.WRITE);
    foo1.setCode("code3");
    em.flush();
}

EDIT:

@Pascal: that's what you mean in the second case?

@Test(expected=OptimisticLockException.class)
public void testLock() {
   EntityManager em = getEntityManager();
   em.getTransaction().begin();
   Foo foo1 = fooDAO.findById(1);
   em.lock(foo1, LockModeType.WRITE);
   fooDAO.createHibernateQuery("update Foo set version=version+1 where id = 1");
   foo1.setCode("code3");
   em.flush();
}

Thanks

+2  A: 

I don't see any concurrent access in this test, there is no reason for it to fail IMO. If you want to test the behavior of optimistic locking with version update, you need to test something like this:

  • Read Foo with Id = X in Persistence Context 1 (version is N)
  • Read Foo with Id = X in Persistence Context 2 (version is N)
  • Do some changes on the foo instance in PC 1
  • Do some changes on the foo instance in PC 2
  • Flush and commit the changes in PC 1 // should be ok (version becomes N + 1)
  • Flush the changes in PC 2 // should throw exception

Using a single persistence context and a SQL query is another option:

  • Read Foo with Id = X in Persistence Context 1 (version is N)
  • Do some changes on the foo instance in PC 1
  • Use SQL to UPDATE Foo set version = version + 1 WHERE id = X
  • Flush the changes in PC 1 // should throw exception

See also

Pascal Thivent