org.hibernate.stat.Statistics Java Examples

The following examples show how to use org.hibernate.stat.Statistics. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void updateItemDescriptions(final EntityManagerFactory emf, String[] newValues, Counts expected) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Item i1 = em.find(Item.class, 1L);
    i1.setDescription(newValues[0]);
    final Item i2 = em.find(Item.class, 2L);
    i2.setDescription(newValues[1]);
    final Item i3 = em.find(Item.class, 3L);
    i3.setDescription(newValues[2]);

    transaction.commit();
    em.close();

    assertRegionStats(expected, Item.class.getName(), stats);
}
 
Example #2
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void rebalanceCpsForPokemons(final EntityManagerFactory emf, Counts expected) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    Pokemon igeldo = em.find(Pokemon.class, 3);
    igeldo.setCp(2707);
    Pokemon godzilla = em.find(Pokemon.class, 248);
    godzilla.setCp(3834);
    Pokemon blissey = em.find(Pokemon.class, 242);
    blissey.setCp(2757);

    transaction.commit();
    em.close();

    assertRegionStats(expected, Pokemon.class.getName(), stats);
}
 
Example #3
Source File: InfinispanHibernateCacheWildflyLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/hibernate-cache/7")
@Produces("application/json")
public String step7_queryEntities() {
   StringBuilder out = new StringBuilder();

   // Query entities, expect:
   // * no cache hits since query is not cached
   // * a query cache miss and query cache put
   ejb.queryEntities(out);
   Statistics stats = getStatistics();
   printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1, out);
   printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1, out);

   return out.toString();
}
 
Example #4
Source File: InfinispanHibernateCacheWildflyLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/hibernate-cache/8")
@Produces("application/json")
public String step8_repeatQuery() {
   StringBuilder out = new StringBuilder();

   // Repeat query, expect:
   // * two cache hits for the number of entities in cache
   // * a query cache hit
   ejb.queryEntities(out);
   Statistics stats = getStatistics();
   printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2, out);
   printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1, out);

   return out.toString();
}
 
Example #5
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
private void printSessionFactoryStats(Statistics statistics, String regionName) {
    SortedMap<String, Map<String, HibernateMetric>> entitiesStatMap = getSecondLevelCacheEntitiesStats(statistics);
    SortedMap<String, Map<String, HibernateMetric>> secondLevelCacheStatMap = getSecondLevelCacheRegionsStats(
            statistics);
    SortedMap<String, Map<String, HibernateMetric>> collectionStatMap = getSecondLevelCacheCollectionsStats(
            statistics);

    logger.debug("--- SECOND LEVEL STATS ---");
    logger.debug("Entities stats of {}: {}", regionName, entitiesStatMap.get(ENTITY_STATS_PREFIX + regionName));
    logger.debug(
            "Collection stats of {} : {}",
            regionName,
            collectionStatMap.get(COLLECTION_STATS_PREFIX + regionName));
    logger.debug(
            "Second level cache stats of {}: {}",
            regionName,
            secondLevelCacheStatMap.get(REGION_STATS_PREFIX + regionName));
    logger.debug("--- --- --- --- --- ---");
}
 
Example #6
Source File: HibernateStatsReporter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void logEntities(StringBuilder builder, String lineSep, Statistics stats) {
    builder.append("Important entities statistics: ").append(lineSep);
    for (String entity : stats.getEntityNames()) {
        EntityStatistics entityStats = stats.getEntityStatistics(entity);
        if (entityStats.getInsertCount() > LIMIT || entityStats.getDeleteCount() > LIMIT || entityStats.getUpdateCount() > LIMIT || entityStats.getLoadCount() > LIMIT || entityStats.getFetchCount() > LIMIT) {
            builder.append(entity).append(" - ")
                    .append("inserted: ").append(entityStats.getInsertCount())
                    .append(", updated: ").append(entityStats.getUpdateCount())
                    .append(", removed: ").append(entityStats.getDeleteCount())
                    .append(", loaded: ").append(entityStats.getLoadCount())
                    .append(", fetched: ").append(entityStats.getFetchCount())
                    .append(lineSep);
        }
    }
    builder.append(lineSep);
}
 
Example #7
Source File: TransactionalTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithRefreshThenRollback() {
    Statistics stats = sessionFactory().getStatistics();
    Long id = null;
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional( "data" );
    id = (Long) s.save( item );
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    item.setName("newdata");
    s.update(item);
    s.flush();
    s.refresh(item);
    s.getTransaction().rollback();
    s.clear();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
 
Example #8
Source File: PaddingInQueryPlanCacheTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testInQueryCachePlan() {
    SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
    Statistics statistics = sessionFactory.getStatistics();
    statistics.clear();

    doInJPA(entityManager -> {
        for (int i = 2; i < 16; i++) {
            getPostByIds(
                    entityManager,
                    IntStream.range(1, i).boxed().toArray(Integer[]::new)
            );
        }
        assertEquals(6L, statistics.getQueryPlanCacheMissCount());

        for (String query : statistics.getQueries()) {
            LOGGER.info("Executed query: {}", query);
        }
    });
}
 
Example #9
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void storeTestPokemons(final EntityManagerFactory emf, Counts expected) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Pokemon igeldo = new Pokemon(3, "Venusaur", 2555);
    em.persist(igeldo);
    final Pokemon godzilla = new Pokemon(248, "Tyranitar", 3670);
    em.persist(godzilla);
    final Pokemon khaleesi = new Pokemon(242, "Blissey", 3219);
    em.persist(khaleesi);

    transaction.commit();
    em.close();

    assertRegionStats(expected, Pokemon.class.getName(), stats);
}
 
Example #10
Source File: JpaRelationshipIntTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludeManyRelations() {
	addTestWithManyRelations(10);

	Statistics stats = sessionFactory.getStatistics();
	stats.clear();

	QuerySpec querySpec = new QuerySpec(TestEntity.class);
	querySpec.includeRelation(Arrays.asList(TestEntity.ATTR_manyRelatedValues));
	List<TestEntity> list = testRepo.findAll(querySpec);

	Assert.assertEquals(10, list.size());
	TestEntity testEntity = list.get(0);

	List<RelatedEntity> manyRelatedValues = testEntity.getManyRelatedValues();
	Assert.assertNotNull(manyRelatedValues);
	Assert.assertEquals(5, manyRelatedValues.size());

	Assert.assertEquals(0, stats.getEntityFetchCount());
	Assert.assertEquals(3, stats.getQueryExecutionCount());
	// TODO issue with map eager loading:
	// Assert.assertEquals(1, stats.getCollectionFetchCount());
}
 
Example #11
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyReadWriteCollection(final EntityManagerFactory emf, int expectedSize,
        Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Trainer t1 = em.find(Trainer.class, 1L);
    final List<Pokemon> pokemons = t1.getPokemons();

    if (pokemons.size() != expectedSize)
        throw new RuntimeException("Incorrect family size: " + pokemons.size() + ", expected: " + expectedSize);

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example #12
Source File: TransactionalTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithRefreshThenRollback() {
    Statistics stats = sessionFactory().getStatistics();
    Long id = null;
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional( "data" );
    id = (Long) s.save( item );
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    item.setName("newdata");
    s.update(item);
    s.flush();
    s.refresh(item);
    s.getTransaction().rollback();
    s.clear();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
 
Example #13
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void storeTestPokemonTrainers(final EntityManagerFactory emf, Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Pokemon rocky = new Pokemon(68, "Rocky", 3056);
    final Pokemon sonGoku = new Pokemon(149, "Son Goku", 3792);
    final Pokemon mmMan = new Pokemon(94, "Marshmallow Man", 2842);
    em.persist(rocky);
    em.persist(sonGoku);
    em.persist(mmMan);
    em.persist(new Trainer(rocky, sonGoku, mmMan));

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example #14
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyFindCitizenByNaturalId(EntityManagerFactory emf, String ssn, String expectedLastName,
        Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Session session = em.unwrap(Session.class);
    final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
    loader.using("ssn", ssn);
    Citizen citizen = loader.load();
    if (!citizen.getLastname().equals(expectedLastName))
        throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expectedLastName);

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example #15
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void updateNaturalId(EntityManagerFactory emf, Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Session session = em.unwrap(Session.class);
    final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
    loader.using("ssn", "45989213T");
    Citizen citizen = loader.load();
    String expected = "Stark";
    if (!citizen.getLastname().equals(expected))
        throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expected);

    citizen.setSsn("78902007R");

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example #16
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static Statistics verifyFindCountryByNaturalId(EntityManagerFactory emf, String callingCode, String expectedName) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Session session = em.unwrap(Session.class);
    final NaturalIdLoadAccess<Country> loader = session.byNaturalId(Country.class);
    loader.using("callingCode", callingCode);
    Country country = loader.load();
    if (!country.getName().equals(expectedName))
        throw new RuntimeException("Incorrect citizen: " + country.getName() + ", expected: " + expectedName);

    transaction.commit();
    em.close();

    return stats;
}
 
Example #17
Source File: TransactionalTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithRefreshThenRollback() {
    Statistics stats = sessionFactory().getStatistics();
    Long id = null;
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional( "data" );
    id = (Long) s.save( item );
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    item.setName("newdata");
    s.update(item);
    s.flush();
    s.refresh(item);
    s.getTransaction().rollback();
    s.clear();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
 
Example #18
Source File: SessionStatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSessionStatistics() throws Exception {
	Session s = openSession();
	Transaction tx = s.beginTransaction();
	Statistics stats = getSessions().getStatistics();
	stats.clear();
	boolean isStats = stats.isStatisticsEnabled();
	stats.setStatisticsEnabled(true);
	Continent europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	SessionStatistics sessionStats = s.getStatistics();
	assertEquals( 0, sessionStats.getEntityKeys().size() );
	assertEquals( 0, sessionStats.getEntityCount() );
	assertEquals( 0, sessionStats.getCollectionKeys().size() );
	assertEquals( 0, sessionStats.getCollectionCount() );
	europe = (Continent) s.get( Continent.class, europe.getId() );
	Hibernate.initialize( europe.getCountries() );
	Hibernate.initialize( europe.getCountries().iterator().next() );
	assertEquals( 2, sessionStats.getEntityKeys().size() );
	assertEquals( 2, sessionStats.getEntityCount() );
	assertEquals( 1, sessionStats.getCollectionKeys().size() );
	assertEquals( 1, sessionStats.getCollectionCount() );
	tx.commit();
	s.close();

	stats.setStatisticsEnabled( isStats);

}
 
Example #19
Source File: HibernateStatisticsCollector.java    From client_java with Apache License 2.0 5 votes vote down vote up
private void addMetricsForQuery(PerQuerySamples samples, ValueProviderPerQuery provider) {

    for (Entry<String, SessionFactory> entry : sessionFactories.entrySet()) {
      SessionFactory sessionFactory = entry.getValue();
      Statistics stats = sessionFactory.getStatistics();
      String unitName = entry.getKey();

      for (String query : stats.getQueries()) {
        samples.addMetric(Arrays.asList(unitName, query), provider.getValue(stats, query));
      }
    }
  }
 
Example #20
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemReadWrite) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemReadWrite) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example #21
Source File: HibernateStatsReporter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void logQueries(StringBuilder builder, String lineSep, Statistics stats) {
    builder.append("Important queries statistics: ").append(lineSep).append(lineSep);
    for (String query : stats.getQueries()) {
        QueryStatistics queryStats = stats.getQueryStatistics(query);

        if (queryStats.getExecutionCount() > LIMIT || (queryStats.getExecutionCount() * queryStats.getExecutionAvgTime() > LIMIT)) {
            builder.append(query).append(lineSep)
                    .append("executionCount=").append(queryStats.getExecutionCount()).append(lineSep)
                    .append("executionAvgTime=").append(queryStats.getExecutionAvgTime()).append(" ms").append(lineSep)
                    .append(lineSep)
                    .append(lineSep);
        }
    }
}
 
Example #22
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testNaturalId() {
    Statistics stats = sessionFactory().getStatistics();
    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite("data");
    item.setNid("123");
    s.save(item);
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
    Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getPutCount());
    
    s = openSession();
    s.beginTransaction();
    item = (ItemReadWrite) s.bySimpleNaturalId(ItemReadWrite.class).load("123");
    assertThat(item).isNotNull();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
    Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getHitCount());

    sessionFactory().getStatistics().logSummary();
}
 
Example #23
Source File: TransactionalTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollection() {
    Long id = null;
    
    Statistics stats = sessionFactory().getStatistics();
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    id = (Long) s.save(item);
    s.flush();
    s.getTransaction().commit();

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    assertThat(item.getEntries()).containsExactly("a", "b", "c");
    s.getTransaction().commit();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getPutCount());
    
    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    assertThat(item.getEntries()).containsExactly("a", "b", "c");
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getHitCount());
}
 
Example #24
Source File: HibernateMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private static SessionFactory createMockSessionFactory(boolean statsEnabled) {
    SessionFactory sf = mock(SessionFactory.class);
    Statistics stats = mock(Statistics.class, invocation -> {
        if (invocation.getMethod().getName().equals("isStatisticsEnabled")) {
            return statsEnabled;
        }
        return 42L;
    });
    when(sf.getStatistics()).thenReturn(stats);
    return sf;
}
 
Example #25
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateWithRefreshThenRollback() {
    Statistics stats = sessionFactory().getStatistics();
    Long id = null;
    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite( "data" );
    id = (Long) s.save( item );
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());

    s = openSession();
    s.beginTransaction();
    item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
    item.setName("newdata");
    s.update(item);
    s.flush();
    s.refresh(item);
    s.getTransaction().rollback();
    s.clear();
    s.close();

    s = openSession();
    s.beginTransaction();
    item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
    Assert.assertEquals("data", item.getName());
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
 
Example #26
Source File: HibernateCacheMonitorController.java    From es with Apache License 2.0 5 votes vote down vote up
@ModelAttribute
public void setCommonData(Model model) {
    Statistics statistics = HibernateUtils.getSessionFactory(em).getStatistics();
    model.addAttribute("statistics", statistics);

    Date startDate = new Date(statistics.getStartTime());
    Date nowDate = new Date();
    long upSeconds = (nowDate.getTime() - startDate.getTime()) / 1000;
    model.addAttribute("upSeconds", upSeconds);
}
 
Example #27
Source File: HibernateEHCacheMain.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	
	System.out.println("Temp Dir:"+System.getProperty("java.io.tmpdir"));
	
	//Initialize Sessions
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	Statistics stats = sessionFactory.getStatistics();
	System.out.println("Stats enabled="+stats.isStatisticsEnabled());
	stats.setStatisticsEnabled(true);
	System.out.println("Stats enabled="+stats.isStatisticsEnabled());
	
	Session session = sessionFactory.openSession();
	Session otherSession = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	Transaction otherTransaction = otherSession.beginTransaction();
	
	printStats(stats, 0);
	
	Employee emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 1);
	
	emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 2);
	
	//clear first level cache, so that second level cache is used
	session.evict(emp);
	emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 3);
	
	emp = (Employee) session.load(Employee.class, 3L);
	printData(emp, stats, 4);
	
	emp = (Employee) otherSession.load(Employee.class, 1L);
	printData(emp, stats, 5);
	
	//Release resources
	transaction.commit();
	otherTransaction.commit();
	sessionFactory.close();
}
 
Example #28
Source File: TransactionalTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemTransactional) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemTransactional) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example #29
Source File: JpaRelationshipIntTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private void testOneToOneUniDirectional(boolean relationship) {
	int n = 10;
	ResourceRepository<OneToOneTestEntity, Serializable> testRepo = client.getRepositoryForType(OneToOneTestEntity.class);
	ResourceRepository<RelatedEntity, Serializable> otherRepo = client.getRepositoryForType(RelatedEntity.class);
	RelationshipRepository relRepo = client.getRepositoryForType(OneToOneTestEntity.class, RelatedEntity.class);

	for (int i = 0; i < n; i++) {
		RelatedEntity related = new RelatedEntity();
		related.setId(12L + i);
		otherRepo.create(related);

		OneToOneTestEntity test = new OneToOneTestEntity();
		test.setId(11L + i);
		if (!relationship) {
			test.setOneRelatedValue(related);
		}
		testRepo.create(test);

		if (relationship) {
			relRepo.setRelation(test, related.getId(), "oneRelatedValue");
		}
	}

	Statistics stats = sessionFactory.getStatistics();
	stats.clear();

	QuerySpec querySpec = new QuerySpec(OneToOneTestEntity.class);
	querySpec.includeRelation(Arrays.asList("oneRelatedValue"));
	ResourceList<OneToOneTestEntity> list = testRepo.findAll(querySpec);
	Assert.assertEquals(10, list.size());
	OneToOneTestEntity testCopy = list.get(0);
	Assert.assertNotNull(testCopy.getOneRelatedValue());
	Assert.assertEquals(12L, testCopy.getOneRelatedValue().getId().longValue());

	// verify no lazy loading and n+1 issues
	Assert.assertEquals(0, stats.getEntityFetchCount());
	Assert.assertEquals(2, stats.getQueryExecutionCount());
	Assert.assertEquals(0, stats.getCollectionFetchCount());
}
 
Example #30
Source File: TransactionalTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollection() {
    Long id = null;
    
    Statistics stats = sessionFactory().getStatistics();
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    id = (Long) s.save(item);
    s.flush();
    s.getTransaction().commit();

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    assertThat(item.getEntries()).containsExactly("a", "b", "c");
    s.getTransaction().commit();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getPutCount());
    
    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    assertThat(item.getEntries()).containsExactly("a", "b", "c");
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getHitCount());
}