Exemplo n.º 1
0
  @Test
  public void testLock() {
    Session s1 = HibernateUtil.getSessionFactory().openSession();

    Long id;
    // store a user
    Transaction ta1 = s1.beginTransaction();
    try {
      YUser u = new YUser("test");
      s1.save(u);
      id = u.getId();
    } finally {
      ta1.commit();
    }

    ta1 = s1.beginTransaction();
    try {
      YUser u1 = (YUser) s1.load(YUser.class, id);
      YUser u2 = (YUser) s1.load(YUser.class, id);

      u1.setDescription("YEAH!");
      assertEquals("YEAH!", u2.getDescription());
    } finally {
      ta1.rollback();
    }

    s1.close();
  }
Exemplo n.º 2
0
  @Test
  public void testLockDifferentSessions() {
    // emulate two different threads
    Session s1 = HibernateUtil.getSessionFactory().openSession();
    Session s2 = HibernateUtil.getSessionFactory().openSession();

    Long id;
    // store a user
    Transaction ta1 = s1.beginTransaction();
    try {
      YUser u = new YUser("test");
      s1.save(u);
      id = u.getId();
    } finally {
      ta1.commit();
    }

    ta1 = s1.beginTransaction();
    Transaction ta2 = s2.beginTransaction();
    try {
      YUser u1 = (YUser) s1.load(YUser.class, id);
      YUser u2 = (YUser) s2.load(YUser.class, id);

      u1.setDescription("overwrite me");
      u2.setDescription("YEAH!");
    } finally {
      ta1.commit();
      try {
        ta2.commit();
        fail("Shouldn't commit. Two different versions!");
      } catch (StaleObjectStateException ex) {
      }
    }

    s1.close();
    s2.close();
  }