1
votes

I know this has been asked before, but I'm trying to test Hibernate's optimistic locking feature using a version field.

I've seen the following answer which outlines how to test this Hibernate 3 : optimistic locking unit test.

Can someone confirm whether or not my test is doing this correctly as I'm not getting the StaleObjectStateException that I'm expecting to see.

@Test(expected = StaleObjectStateException.class)
public void optimisticLockingTest() {
    DummyEntity entity= new DummyEntity("name");
    entityDao.persist(entity);

    entityDao.detach(entity);
    entity.setName("new name");

    // Get new instance of the same entity
    final DummyEntity newEntity = entityDao.findById(entity.getId());
    newEntity.setName("Different name");
    entityDao.persist(newEntity);

    entity = entityDao.merge(entity );
    entityDao.persist(entity);
}
1
It just calls entityManager.detach(entity). Where entityManager is annotated with @PersistenceContext - wybourn

1 Answers

2
votes

The version is incremented just before the update to the database happens.

As all this code is in one transaction, when you do entityDao.findById(entity.getId()); the entity.getVersion() would still be 0 so both entity and newEntity will have same Id and same Version.

You need to force the update to the database after each persist() and merge() with either EntityManager.flush() or by programmatically start/commit transactions.

So the code would be:

    DummyEntity entity= new DummyEntity("name");
    entityDao.persist(entity);
    entityDao.flush();
    entityDao.detach(entity);

    final DummyEntity newEntity = entityDao.findById(entity.getId());
    newEntity.setName("Different name");
    entityDao.persist(newEntity);
    entityDao.flush();

    entity.setName("new name");
    entity = entityDao.merge(entity );
    entityDao.persist(entity);