Example #1
0
 @Test
 public void insertNewEntity() {
   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("testing", entity.getValue());
   Assert.assertEquals(new Integer(0), entity.getVersion());
   Assert.assertEquals(new Long(1), entity.getId());
 }
Example #2
0
  @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();
      }
    }
  }