org.hibernate.stat.QueryStatistics Java Examples

The following examples show how to use org.hibernate.stat.QueryStatistics. 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: HibernateQueryMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private Statistics createQueryStatisticsMock(String query) {
    Statistics statistics = mock(Statistics.class);
    QueryStatistics queryStatistics = mock(QueryStatistics.class, invocation -> 43L);
    when(statistics.getQueries()).thenReturn(new String[]{query});
    when(statistics.getQueryStatistics(query)).thenReturn(queryStatistics);
    return statistics;
}
 
Example #2
Source File: HibernateStatisticsCollectorTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  registry = new CollectorRegistry();
  sessionFactory = mock(SessionFactory.class);
  statistics = mock(Statistics.class);
  queryStatistics = mock(QueryStatistics.class);
  when(sessionFactory.getStatistics()).thenReturn(statistics);
}
 
Example #3
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 #4
Source File: HibernateQueryMetrics.java    From micrometer with Apache License 2.0 4 votes vote down vote up
void registerQueryMetric(Statistics statistics) {
    for (String query : statistics.getQueries()) {
        QueryStatistics queryStatistics = statistics.getQueryStatistics(query);

        FunctionCounter.builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheHitCount)
                .tags(tags)
                .tags("result", "hit", "query", query)
                .description("Number of query cache hits")
                .register(meterRegistry);

        FunctionCounter.builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheMissCount)
                .tags(tags)
                .tags("result", "miss", "query", query)
                .description("Number of query cache misses")
                .register(meterRegistry);

        FunctionCounter.builder("hibernate.query.cache.puts", queryStatistics, QueryStatistics::getCachePutCount)
                .tags(tags)
                .tags("query", query)
                .description("Number of cache puts for a query")
                .register(meterRegistry);

        FunctionTimer.builder("hibernate.query.execution.total", queryStatistics, QueryStatistics::getExecutionCount, QueryStatistics::getExecutionTotalTime, TimeUnit.MILLISECONDS)
                .tags(tags)
                .tags("query", query)
                .description("Query executions")
                .register(meterRegistry);

        TimeGauge.builder("hibernate.query.execution.max", queryStatistics, TimeUnit.MILLISECONDS, QueryStatistics::getExecutionMaxTime)
                .tags(tags)
                .tags("query", query)
                .description("Query maximum execution time")
                .register(meterRegistry);

        TimeGauge.builder("hibernate.query.execution.min", queryStatistics, TimeUnit.MILLISECONDS, QueryStatistics::getExecutionMinTime)
                .tags(tags)
                .tags("query", query)
                .description("Query minimum execution time")
                .register(meterRegistry);

        FunctionCounter.builder("hibernate.query.execution.rows", queryStatistics, QueryStatistics::getExecutionRowCount)
                .tags(tags)
                .tags("query", query)
                .description("Number of rows processed for a query")
                .register(meterRegistry);
    }
}
 
Example #5
Source File: StatisticsService.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * @see StatisticsServiceMBean#getQueryStatistics(java.lang.String)
 */
public QueryStatistics getQueryStatistics(String hql) {
	return stats.getQueryStatistics(hql);
}
 
Example #6
Source File: QueryCacheTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testQueryCacheInvalidation() throws Exception {
	
	getSessions().evictQueries();
	getSessions().getStatistics().clear();

	final String queryString = "from Item i where i.name='widget'";

	Session s = openSession();
	Transaction t = s.beginTransaction();
	s.createQuery( queryString ).setCacheable(true).list();
	Item i = new Item();
	i.setName("widget");
	i.setDescription("A really top-quality, full-featured widget.");
	s.save(i);
	t.commit();
	s.close();
	
	QueryStatistics qs = s.getSessionFactory().getStatistics().getQueryStatistics( queryString );
	EntityStatistics es = s.getSessionFactory().getStatistics().getEntityStatistics( Item.class.getName() );

	Thread.sleep(200);

	s = openSession();
	t = s.beginTransaction();
	List result = s.createQuery( queryString ).setCacheable(true).list();
	assertEquals( result.size(), 1 );
	t.commit();
	s.close();
	
	assertEquals( qs.getCacheHitCount(), 0 );
			
	s = openSession();
	t = s.beginTransaction();
	result = s.createQuery( queryString ).setCacheable(true).list();
	assertEquals( result.size(), 1 );
	t.commit();
	s.close();
	
	assertEquals( qs.getCacheHitCount(), 1 );
	assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 0 );
	
	s = openSession();
	t = s.beginTransaction();
	result = s.createQuery( queryString ).setCacheable(true).list();
	assertEquals( result.size(), 1 );
	assertTrue( Hibernate.isInitialized( result.get(0) ) );
	i = (Item) result.get(0);
	i.setName("Widget");
	t.commit();
	s.close();
	
	assertEquals( qs.getCacheHitCount(), 2 );
	assertEquals( qs.getCacheMissCount(), 2 );
	assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 0 );

	Thread.sleep(200);

	s = openSession();
	t = s.beginTransaction();
	result = s.createQuery( queryString ).setCacheable(true).list();
	if ( dialectIsCaseSensitive("i.name='widget' should not match on case sensitive database.") ) {
		assertEquals( result.size(), 0 );
	}
	i = (Item) s.get( Item.class, new Long(i.getId()) );
	assertEquals( i.getName(), "Widget" );
	
	s.delete(i);
	t.commit();
	s.close();

	assertEquals( qs.getCacheHitCount(), 2 );
	assertEquals( qs.getCacheMissCount(), 3 );
	assertEquals( qs.getCachePutCount(), 3 );
	assertEquals( qs.getExecutionCount(), 3 );
	assertEquals( es.getFetchCount(), 0 ); //check that it was being cached
	
}
 
Example #7
Source File: QueryCacheTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testQueryCacheFetch() throws Exception {
	
	getSessions().evictQueries();
	getSessions().getStatistics().clear();
	
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Item i = new Item();
	i.setName("widget");
	i.setDescription("A really top-quality, full-featured widget.");
	Item i2 = new Item();
	i2.setName("other widget");
	i2.setDescription("Another decent widget.");
	s.persist(i);
	s.persist(i2);
	t.commit();
	s.close();

	final String queryString = "from Item i where i.name like '%widget'";

	QueryStatistics qs = s.getSessionFactory().getStatistics().getQueryStatistics( queryString );

	Thread.sleep(200);

	s = openSession();
	t = s.beginTransaction();
	List result = s.createQuery( queryString ).setCacheable(true).list();
	assertEquals( result.size(), 2 );
	t.commit();
	s.close();
	
	assertEquals( qs.getCacheHitCount(), 0 );
	assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 0 );
	
	getSessions().evict(Item.class);
			
	s = openSession();
	t = s.beginTransaction();
	result = s.createQuery( queryString ).setCacheable(true).list();
	assertEquals( result.size(), 2 );
	assertTrue( Hibernate.isInitialized( result.get(0) ) );
	assertTrue( Hibernate.isInitialized( result.get(1) ) );
	t.commit();
	s.close();
	
	assertEquals( qs.getCacheHitCount(), 1 );
	assertEquals( s.getSessionFactory().getStatistics().getEntityFetchCount(), 1 );

	s = openSession();
	t = s.beginTransaction();
	s.createQuery("delete Item").executeUpdate();
	t.commit();
	s.close();
	
}
 
Example #8
Source File: StatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testQueryStatGathering() {
		Statistics stats = getSessions().getStatistics();
		stats.clear();

		Session s = openSession();
		Transaction tx = s.beginTransaction();
		fillDb(s);
		tx.commit();
		s.close();

		s = openSession();
		tx = s.beginTransaction();
		final String continents = "from Continent";
		int results = s.createQuery( continents ).list().size();
		QueryStatistics continentStats = stats.getQueryStatistics( continents );
		assertNotNull( "stats were null",  continentStats );
		assertEquals( "unexpected execution count", 1, continentStats.getExecutionCount() );
		assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
		long maxTime = continentStats.getExecutionMaxTime();
		assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
//		assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );

		Iterator itr = s.createQuery( continents ).iterate();
		// iterate() should increment the execution count
		assertEquals( "unexpected execution count", 2, continentStats.getExecutionCount() );
		// but should not effect the cumulative row count
		assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
		Hibernate.close( itr );

		ScrollableResults scrollableResults = s.createQuery( continents ).scroll();
		// same deal with scroll()...
		assertEquals( "unexpected execution count", 3, continentStats.getExecutionCount() );
		assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
		scrollableResults.close();
		tx.commit();
		s.close();

		// explicitly check that statistics for "split queries" get collected
		// under the original query
		stats.clear();
		s = openSession();
		tx = s.beginTransaction();
		final String localities = "from Locality";
		results = s.createQuery( localities ).list().size();
		QueryStatistics localityStats = stats.getQueryStatistics( localities );
		assertNotNull( "stats were null",  localityStats );
		// ...one for each split query
		assertEquals( "unexpected execution count", 2, localityStats.getExecutionCount() );
		assertEquals( "unexpected row count", results, localityStats.getExecutionRowCount() );
		maxTime = localityStats.getExecutionMaxTime();
		assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
//		assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
		tx.commit();
		s.close();
		assertFalse( s.isOpen() );

		// native sql queries
		stats.clear();
		s = openSession();
		tx = s.beginTransaction();
		final String sql = "select id, name from Country";
		results = s.createSQLQuery( sql ).addEntity( Country.class ).list().size();
		QueryStatistics sqlStats = stats.getQueryStatistics( sql );
		assertNotNull( "sql stats were null", sqlStats );
		assertEquals( "unexpected execution count", 1, sqlStats.getExecutionCount() );
		assertEquals( "unexpected row count", results, sqlStats.getExecutionRowCount() );
		maxTime = sqlStats.getExecutionMaxTime();
		assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
//		assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
		tx.commit();
		s.close();

		s = openSession();
		tx = s.beginTransaction();
		cleanDb( s );
		tx.commit();
		s.close();
	}
 
Example #9
Source File: ASTParserLoadingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testDynamicInstantiationQueries() throws Exception {

		createTestBaseData();

		Session session = openSession();

		List results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertClassAssignability( results.get( 0 ).getClass(), Animal.class );

		Iterator iter = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		assertTrue( "Incorrect return type", iter.next() instanceof Animal );

		results = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof List );
		assertEquals( "Incorrect return type", ( (List) results.get( 0 ) ).size(), 2 );

		results = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof List );
		assertEquals( "Incorrect return type", ( (List) results.get( 0 ) ).size(), 2 );

		iter = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		Object obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof List );
		assertEquals( "Incorrect return type", ( (List) obj ).size(), 2 );

		iter = ((org.hibernate.classic.Session)session).iterate( "select new list(an.description, an.bodyWeight) from Animal an" );
		assertTrue( "Incorrect result size", iter.hasNext() );
		obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof List );
		assertEquals( "Incorrect return type", ( (List) obj ).size(), 2 );

		results = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) results.get( 0 ) ).size(), 2 );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("0") );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("1") );

		results = session.createQuery( "select new map(an.description as descr, an.bodyWeight as bw) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) results.get( 0 ) ).size(), 2 );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("descr") );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("bw") );

		iter = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) obj ).size(), 2 );

		ScrollableResults sr = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).scroll();
		assertTrue( "Incorrect result size", sr.next() );
		obj = sr.get(0);
		assertTrue( "Incorrect return type", obj instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) obj ).size(), 2 );
		sr.close();

		sr = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).scroll();
		assertTrue( "Incorrect result size", sr.next() );
		assertTrue( "Incorrect return type", sr.get(0) instanceof Animal );
		sr.close();

		// caching...
		QueryStatistics stats = getSessions().getStatistics().getQueryStatistics( "select new Animal(an.description, an.bodyWeight) from Animal an" );
		results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" )
				.setCacheable( true )
				.list();
		assertEquals( "incorrect result size", 2, results.size() );
		assertClassAssignability( Animal.class, results.get( 0 ).getClass() );
		long initCacheHits = stats.getCacheHitCount();
		results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" )
				.setCacheable( true )
				.list();
		assertEquals( "dynamic intantiation query not served from cache", initCacheHits + 1, stats.getCacheHitCount() );
		assertEquals( "incorrect result size", 2, results.size() );
		assertClassAssignability( Animal.class, results.get( 0 ).getClass() );

		session.close();

		destroyTestBaseData();
	}
 
Example #10
Source File: StatisticsWrapper.java    From lemon with Apache License 2.0 4 votes vote down vote up
public QueryStatistics getQueryStatistics(String queryString) {
    return null;
}