em.persist(entity1); // persist entity 1
EhCacheEntity entity2 = prepareData("2", 32);
em.persist(entity2); // persist entity 1
Cache l2Cache = (Cache) em.getEntityManagerFactory().getCache();
PersistenceDelegator persistenceDelegator = null;
persistenceDelegator = getPersistenceDelegator(persistenceDelegator);
// get node from first level cache.
Node node1 = persistenceDelegator
.getPersistenceCache()
.getMainCache()
.getNodeFromCache(
entity1,
KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),
entity1.getClass()), persistenceDelegator);
// check if it is present in second level cache.
EhCacheEntity foundNode1 = (EhCacheEntity) l2Cache.get(node1.getNodeId());
Assert.assertNotNull(foundNode1);
Assert.assertEquals(foundNode1, node1.getData()); // should be same
// object.
// remove entity 1.
em.remove(entity1);
Node node2 = persistenceDelegator
.getPersistenceCache()
.getMainCache()
.getNodeFromCache(
entity2,
KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),
entity1.getClass()), persistenceDelegator);
Assert.assertNotNull(l2Cache.get(node2.getNodeId()));
EhCacheEntity foundNode2 = (EhCacheEntity) l2Cache.get(node2.getNodeId());
Assert.assertEquals(foundNode2, node2.getData()); // should be same
// object.
Assert.assertNull(l2Cache.get(node1.getNodeId()));
entity1.setAge(99);
em.persist(entity1);
em.flush();
// get node from first level cache.
node1 = persistenceDelegator
.getPersistenceCache()
.getMainCache()
.getNodeFromCache(
entity1,
KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),
entity1.getClass()), persistenceDelegator);
// check if it is present in second level cache.
foundNode1 = (EhCacheEntity) l2Cache.get(node1.getNodeId());
Assert.assertNotNull(foundNode1);
Assert.assertEquals(foundNode1, node1.getData()); // should be same
// object.
Assert.assertEquals(foundNode1.getAge(), new Integer(99));
Assert.assertEquals(foundNode1.getAge(), entity1.getAge());
em.clear(); // evict all.
Assert.assertNull(l2Cache.get(node2.getNodeId()));
}