Search in sources :

Example 6 with QueryStatistics

use of org.hibernate.stat.QueryStatistics in project wildfly by wildfly.

the class SFSB4LC method entityCacheCheck.

/**
 * Performs 2 query calls, first call put entity in the cache and second should hit the cache
 *
 * @param id Employee's id in the query
 */
public String entityCacheCheck(int id) {
    // the nextTimestamp from infinispan is "return System.currentTimeMillis()"
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        return e.getMessage();
    }
    EntityManager em = emf.createEntityManager();
    Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
    stats.clear();
    try {
        String queryString = "from Employee e where e.id = " + id;
        QueryStatistics queryStats = stats.getQueryStatistics(queryString);
        Query query = em.createQuery(queryString);
        query.setHint("org.hibernate.cacheable", true);
        // query - this call should fill the cache
        query.getResultList();
        assertEquals("Expected 1 miss in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheMissCount());
        assertEquals("Expected 1 put in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCachePutCount());
        assertEquals("Expected no hits in cache" + generateQueryCacheStats(queryStats), 0, queryStats.getCacheHitCount());
        // query - second call should hit cache
        query.getResultList();
        assertEquals("Expected 1 hit in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheHitCount());
    } catch (AssertionError e) {
        return e.getMessage();
    } finally {
        em.close();
    }
    return "OK";
}
Also used : EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) QueryStatistics(org.hibernate.stat.QueryStatistics) QueryStatistics(org.hibernate.stat.QueryStatistics) Statistics(org.hibernate.stat.Statistics)

Example 7 with QueryStatistics

use of org.hibernate.stat.QueryStatistics in project hibernate-orm by hibernate.

the class HibernateCacheTest method testGeneralUsage.

@Test
public void testGeneralUsage() {
    EventManager mgr = new EventManager(sessionFactory());
    Statistics stats = sessionFactory().getStatistics();
    // create 3 persons Steve, Orion, Tim
    Person stevePerson = new Person();
    stevePerson.setFirstname("Steve");
    stevePerson.setLastname("Harris");
    Long steveId = mgr.createAndStorePerson(stevePerson);
    mgr.addEmailToPerson(steveId, "steve@tc.com");
    mgr.addEmailToPerson(steveId, "sharrif@tc.com");
    mgr.addTalismanToPerson(steveId, "rabbit foot");
    mgr.addTalismanToPerson(steveId, "john de conqueroo");
    PhoneNumber p1 = new PhoneNumber();
    p1.setNumberType("Office");
    p1.setPhone(111111);
    mgr.addPhoneNumberToPerson(steveId, p1);
    PhoneNumber p2 = new PhoneNumber();
    p2.setNumberType("Home");
    p2.setPhone(222222);
    mgr.addPhoneNumberToPerson(steveId, p2);
    Person orionPerson = new Person();
    orionPerson.setFirstname("Orion");
    orionPerson.setLastname("Letizi");
    Long orionId = mgr.createAndStorePerson(orionPerson);
    mgr.addEmailToPerson(orionId, "orion@tc.com");
    mgr.addTalismanToPerson(orionId, "voodoo doll");
    Long timId = mgr.createAndStorePerson("Tim", "Teck");
    mgr.addEmailToPerson(timId, "teck@tc.com");
    mgr.addTalismanToPerson(timId, "magic decoder ring");
    Long engMeetingId = mgr.createAndStoreEvent("Eng Meeting", stevePerson, new Date());
    mgr.addPersonToEvent(steveId, engMeetingId);
    mgr.addPersonToEvent(orionId, engMeetingId);
    mgr.addPersonToEvent(timId, engMeetingId);
    Long docMeetingId = mgr.createAndStoreEvent("Doc Meeting", orionPerson, new Date());
    mgr.addPersonToEvent(steveId, docMeetingId);
    mgr.addPersonToEvent(orionId, docMeetingId);
    for (Event event : (List<Event>) mgr.listEvents()) {
        mgr.listEmailsOfEvent(event.getId());
    }
    QueryStatistics queryStats = stats.getQueryStatistics("from Event");
    assertThat("Cache Miss Count", queryStats.getCacheMissCount(), equalTo(1L));
    assertThat("Cache Hit Count", queryStats.getCacheHitCount(), equalTo(0L));
    assertThat("Cache Put Count", queryStats.getCachePutCount(), equalTo(1L));
}
Also used : EventManager(org.hibernate.test.domain.EventManager) QueryStatistics(org.hibernate.stat.QueryStatistics) PhoneNumber(org.hibernate.test.domain.PhoneNumber) Event(org.hibernate.test.domain.Event) List(java.util.List) QueryStatistics(org.hibernate.stat.QueryStatistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Statistics(org.hibernate.stat.Statistics) Person(org.hibernate.test.domain.Person) Date(java.util.Date) Test(org.junit.Test)

Example 8 with QueryStatistics

use of org.hibernate.stat.QueryStatistics in project OpenOLAT by OpenOLAT.

the class HibernateQueriesController method loadModel.

public void loadModel() {
    Statistics statistics = dbInstance.getStatistics();
    String[] queries = statistics.getQueries();
    List<QueryInfos> infos = new ArrayList<>(queries.length);
    for (String query : queries) {
        QueryStatistics queryStats = statistics.getQueryStatistics(query);
        infos.add(new QueryInfos(query, queryStats));
    }
    tableModel.setObjects(infos);
    table.reset();
}
Also used : QueryStatistics(org.hibernate.stat.QueryStatistics) ArrayList(java.util.ArrayList) QueryStatistics(org.hibernate.stat.QueryStatistics) Statistics(org.hibernate.stat.Statistics)

Example 9 with QueryStatistics

use of org.hibernate.stat.QueryStatistics in project microservices by pwillhan.

the class SecondLevel method cacheQueryResults.

@Test
public void cacheQueryResults() throws Exception {
    CacheTestData testData = storeTestData();
    Long USER_ID = testData.users.getFirstId();
    Long ITEM_ID = testData.items.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        // Clear the Item entity cache region
        JPA.getEntityManagerFactory().getCache().evict(Item.class);
        Statistics stats = JPA.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
        {
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            String queryString = "select i from Item i where i.name like :n";
            /* 
                   You have to enable caching for a particular query. Without
                   the <code>org.hibernate.cachable</code> hint, the
                   result won't be stored in the query result cache.
                 */
            Query query = em.createQuery(queryString).setParameter("n", "I%").setHint("org.hibernate.cacheable", true);
            /* 
                   Hibernate will now execute the SQL query and retrieve the
                   result set into memory.                 */
            List<Item> items = query.getResultList();
            assertEquals(items.size(), 3);
            /* 
                   Using the statistics API, you can find out more details.
                   This is the first time you execute this query, so you get
                   a cache miss, not a hit. Hibernate puts the query and
                   its result into the cache. If you run the exact same query
                   again, the result will be from the cache.
                 */
            QueryStatistics queryStats = stats.getQueryStatistics(queryString);
            assertEquals(queryStats.getCacheHitCount(), 0);
            assertEquals(queryStats.getCacheMissCount(), 1);
            assertEquals(queryStats.getCachePutCount(), 1);
            /* 
                   The actual entity instance data retrieved in the result set is
                   stored in the entity cache region, not in the query result cache.
                 */
            SecondLevelCacheStatistics itemCacheStats = stats.getSecondLevelCacheStatistics(Item.class.getName());
            assertEquals(itemCacheStats.getElementCountInMemory(), 3);
            tx.commit();
            em.close();
        }
        {
            // Execute the query again, hitting the cache
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            String queryString = "select i from Item i where i.name like :n";
            List<Item> items = em.createQuery(queryString).setParameter("n", "I%").setHint("org.hibernate.cacheable", true).getResultList();
            assertEquals(items.size(), 3);
            QueryStatistics queryStats = stats.getQueryStatistics(queryString);
            assertEquals(queryStats.getCacheHitCount(), 1);
            assertEquals(queryStats.getCacheMissCount(), 1);
            assertEquals(queryStats.getCachePutCount(), 1);
            tx.commit();
            em.close();
        }
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) SessionFactory(org.hibernate.SessionFactory) EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) QueryStatistics(org.hibernate.stat.QueryStatistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) List(java.util.List) Statistics(org.hibernate.stat.Statistics) QueryStatistics(org.hibernate.stat.QueryStatistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) NaturalIdCacheStatistics(org.hibernate.stat.NaturalIdCacheStatistics) Test(org.testng.annotations.Test) JPATest(org.jpwh.env.JPATest)

Example 10 with QueryStatistics

use of org.hibernate.stat.QueryStatistics in project openmrs-core by openmrs.

the class HibernateContextDAO method showUsageStatistics.

/**
 * Convenience method to print out the hibernate cache usage stats to the log
 */
private void showUsageStatistics() {
    if (sessionFactory.getStatistics().isStatisticsEnabled()) {
        log.debug("Getting query statistics: ");
        Statistics stats = sessionFactory.getStatistics();
        for (String query : stats.getQueries()) {
            log.info("QUERY: " + query);
            QueryStatistics qstats = stats.getQueryStatistics(query);
            log.info("Cache Hit Count : " + qstats.getCacheHitCount());
            log.info("Cache Miss Count: " + qstats.getCacheMissCount());
            log.info("Cache Put Count : " + qstats.getCachePutCount());
            log.info("Execution Count : " + qstats.getExecutionCount());
            log.info("Average time    : " + qstats.getExecutionAvgTime());
            log.info("Row Count       : " + qstats.getExecutionRowCount());
        }
    }
}
Also used : QueryStatistics(org.hibernate.stat.QueryStatistics) Statistics(org.hibernate.stat.Statistics) QueryStatistics(org.hibernate.stat.QueryStatistics)

Aggregations

QueryStatistics (org.hibernate.stat.QueryStatistics)16 Statistics (org.hibernate.stat.Statistics)9 List (java.util.List)8 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)7 Session (org.hibernate.Session)6 Transaction (org.hibernate.Transaction)5 EntityManager (javax.persistence.EntityManager)4 Query (javax.persistence.Query)4 CacheRegionStatistics (org.hibernate.stat.CacheRegionStatistics)3 Date (java.util.Date)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 ScrollableResults (org.hibernate.ScrollableResults)2 SessionFactory (org.hibernate.SessionFactory)2 EntityStatistics (org.hibernate.stat.EntityStatistics)2 SecondLevelCacheStatistics (org.hibernate.stat.SecondLevelCacheStatistics)2 HashMap (java.util.HashMap)1 UserTransaction (javax.transaction.UserTransaction)1 StatsEntry (org.bedework.calfacade.BwStats.StatsEntry)1