Item item = new Item( "Mouse", "Micro$oft mouse" );
Distributor res = new Distributor();
res.setName( "Bruce" );
item.setDistributors( new HashSet<Distributor>() );
item.getDistributors().add( res );
Statistics stats = ( (HibernateEntityManagerFactory) factory ).getSessionFactory().getStatistics();
stats.clear();
stats.setStatisticsEnabled( true );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist( res );
em.persist( item );
assertTrue( em.contains( item ) );
em.getTransaction().commit();
em.close();
assertEquals( 1, stats.getSecondLevelCachePutCount() );
assertEquals( 0, stats.getSecondLevelCacheHitCount() );
em = factory.createEntityManager();
em.getTransaction().begin();
Item second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
assertEquals( 1, stats.getSecondLevelCacheHitCount() );
em.getTransaction().commit();
em.close();
em = factory.createEntityManager();
em.getTransaction().begin();
second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
assertEquals( 3, stats.getSecondLevelCacheHitCount() );
for ( Distributor distro : second.getDistributors() ) {
em.remove( distro );
}
em.remove( second );
em.getTransaction().commit();
em.close();
stats.clear();
stats.setStatisticsEnabled( false );
}