Hibernate statistics, execution context and ability to collect executed query to statistics

Hi all,

I’m trying to collect execution statistics (execution time) about all executed queries (by client’s request) per every query. I’m aware that Hibernate produces accumulated stats where I can see something like this

Session Metrics {\n    XYZ nanoseconds spent acquiring 1 JDBC connections;\n    0 nanoseconds spent releasing 0 JDBC connections;\n    XYZ nanoseconds spent preparing 17 JDBC statements;\n    XYZ nanoseconds spent executing 17 JDBC statements ...

but I’m interested it stats per query.
So, I’ve created an own implementation of org.hibernate.stat.spi.StatisticsImplementor, where I have the queryExecuted method, which teoretically should help to collect stuff I needed. But there is a small problem - in the org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl#doExecuteQuery somewhat around line 299 there is this check:

		if ( executionContext.hasQueryExecutionToBeAddedToStatistics()
				&& jdbcValues instanceof JdbcValuesResultSetImpl ) {
			stats = statistics.isStatisticsEnabled();
			if ( stats ) {
				startTime = System.nanoTime();
		else {
			stats = false;

which is kind of problematic: for example, when executionContext is an instance of org.hibernate.loader.ast.internal.CollectionLoaderSingleKey.CollectionLoaderSingleKeyExecutionContext method hasQueryExecutionToBeAddedToStatistics always will return false (as it defined in org.hibernate.sql.exec.spi.ExecutionContext#hasQueryExecutionToBeAddedToStatistics) and org.hibernate.stat.spi.StatisticsImplementor#queryExecuted won’t be executed.

So my questions are: is this behaviour intentional? Is there a way to set org.hibernate.sql.exec.spi.ExecutionContext#hasQueryExecutionToBeAddedToStatistics to return true for all type of queries/execution contexts?

Thanks for help

You can create a JIRA ticket for this enhancement request/bug report. I guess we’d consider it a bug if this worked in 5.

I don’t think this is intentional, but statistics haven’t been well defined so far, so it’s hard to say.

Hi, thanks for the reply… Tried with Hibernate 5 with the same result: got “recorded” 1 select out of 20 selects… I think this is definitely a bug, considering that statistics won’t collect all queries.

Gues I’ll submit a Jira ticket.