Hibernate provides a number of metrics, from very basic to the specialized information only relevant in certain scenarios. All available counters are described in the
Statistics interface API, in three categories:
Metrics related to the general
Session usage, such as number of open sessions, retrieved JDBC connections, etc.
Metrics related to he entities, collections, queries, and caches as a whole (aka global metrics),
Detailed metrics related to a particular entity, collection, query or cache region.
For exampl,e you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Beware that the number of milliseconds is subject to approximation in Java. Hibernate is tied to the JVM precision, on some platforms this might even only be accurate to 10 seconds.
Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the
QueryStatistics API Javadoc for more information. The following code shows a simple example:
Statistics stats = HibernateUtil.sessionFactory.getStatistics();
double queryCacheHitCount = stats.getQueryCacheHitCount();
double queryCacheMissCount = stats.getQueryCacheMissCount();
double queryCacheHitRatio =
queryCacheHitCount / (queryCacheHitCount + queryCacheMissCount);
log.info("Query Hit ratio:" + queryCacheHitRatio);
EntityStatistics entityStats =
stats.getEntityStatistics( Cat.class.getName() );
long changes =
log.info(Cat.class.getName() + " changed " + changes + "times" );
To work on all entities, collections, queries and region caches, you can retrieve the list of names of entities, collections, queries and region caches with the following methods: