@Test(expected = se.spagettikod.optimist.ModifiedByAnotherUserException.class) public void modifiedByAnotherUser() { SqlSession firstSession = MyBatisTestUtil.getSession(); Entity entity = new Entity(); entity.setValue("firstEdit"); EntityMapper firstMapper = firstSession.getMapper(EntityMapper.class); firstMapper.insertEntity(entity); firstSession.commit(); Assert.assertEquals(new Integer(0), entity.getVersion()); // Load same entity in second session SqlSession secondSession = MyBatisTestUtil.getSession(); Entity secondEntity = new Entity(); Long identity = entity.getId(); EntityMapper secondMapper = secondSession.getMapper(EntityMapper.class); secondEntity = secondMapper.getById(identity); Assert.assertEquals(new Integer(0), secondEntity.getVersion()); // Modify entity in first session entity = firstMapper.getById(entity.getId()); entity.setValue("secondEdit"); firstMapper.updateEntity(entity); firstSession.commit(); firstSession.close(); Assert.assertEquals(new Integer(1), entity.getVersion()); secondEntity.setValue("thirdEdit"); try { secondMapper.updateEntity(secondEntity); } catch (PersistenceException e) { if (e.getCause() instanceof ModifiedByAnotherUserException) { throw (ModifiedByAnotherUserException) e.getCause(); } else { throw e; } } finally { if (secondSession != null) { secondSession.close(); } } }
@Test public void updateEntity() { Entity entity = new Entity(); entity.setValue("testing"); SqlSession session = MyBatisTestUtil.getSession(); EntityMapper mapper = session.getMapper(EntityMapper.class); try { mapper.insertEntity(entity); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } Assert.assertEquals(new Integer(0), entity.getVersion()); Long identity = entity.getId(); session = MyBatisTestUtil.getSession(); mapper = session.getMapper(EntityMapper.class); entity = mapper.getById(identity); entity.setValue("tjoho"); try { mapper.updateEntity(entity); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } Assert.assertEquals("tjoho", entity.getValue()); Assert.assertEquals(new Integer(1), entity.getVersion()); }