Search in sources :

Example 1 with VersionedItem

use of org.hibernate.test.domain.VersionedItem in project hibernate-orm by hibernate.

the class HibernateCacheTest method testStaleWritesLeaveCacheConsistent.

@Test
public void testStaleWritesLeaveCacheConsistent() {
    Session s = sessionFactory().openSession();
    Transaction txn = s.beginTransaction();
    VersionedItem item = new VersionedItem();
    item.setName("steve");
    item.setDescription("steve's item");
    s.save(item);
    txn.commit();
    s.close();
    Long initialVersion = item.getVersion();
    // manually revert the version property
    item.setVersion(item.getVersion() - 1);
    try {
        s = sessionFactory().openSession();
        txn = s.beginTransaction();
        s.update(item);
        txn.commit();
        s.close();
        fail("expected stale write to fail");
    } catch (Throwable expected) {
        // expected behavior here
        if (txn != null) {
            try {
                txn.rollback();
            } catch (Throwable ignore) {
            }
        }
    } finally {
        if (s != null && s.isOpen()) {
            try {
                s.close();
            } catch (Throwable ignore) {
            }
        }
    }
    // check the version value in the cache...
    SecondLevelCacheStatistics slcs = sessionFactory().getStatistics().getSecondLevelCacheStatistics(REGION_PREFIX + VersionedItem.class.getName());
    assertNotNull(slcs);
    final Map entries = slcs.getEntries();
    Object entry = entries.get(item.getId());
    Long cachedVersionValue;
    if (entry instanceof SoftLock) {
    //FIXME don't know what to test here
    //cachedVersionValue = new Long( ( (ReadWriteCache.Lock) entry).getUnlockTimestamp() );
    } else {
        cachedVersionValue = (Long) ((Map) entry).get("_version");
        assertThat(initialVersion, equalTo(cachedVersionValue));
    }
    // cleanup
    s = sessionFactory().openSession();
    txn = s.beginTransaction();
    item = (VersionedItem) s.load(VersionedItem.class, item.getId());
    s.delete(item);
    txn.commit();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) VersionedItem(org.hibernate.test.domain.VersionedItem) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Map(java.util.Map) Session(org.hibernate.Session) SoftLock(org.hibernate.cache.spi.access.SoftLock) Test(org.junit.Test)

Aggregations

Map (java.util.Map)1 Session (org.hibernate.Session)1 Transaction (org.hibernate.Transaction)1 SoftLock (org.hibernate.cache.spi.access.SoftLock)1 SecondLevelCacheStatistics (org.hibernate.stat.SecondLevelCacheStatistics)1 VersionedItem (org.hibernate.test.domain.VersionedItem)1 Test (org.junit.Test)1