[Hibernate] – How to use Hibernate Statistics ?

Hibernate Statistics is a Hibernate class where we can back several methods that can help us to find bottlenecks.

How to configure it ?

@Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) {
    ...    
    props.setProperty("hibernate.generate_statistics", "true");
    ...
}

After enabling Hibernate Statistics, we need to access the API that provides all of these statistics. As it is specific Hibernate and not part of the JPA, we need to get the instance of a Hibernate SessionFactory internal object called and, from it, take the instance of the object Statistics:

@Bean
public Statistics statistics(EntityManagerFactory emf) { 
    return emf.unwrap(SessionFactory.class).getStatistics();
}

How to use it ?

Below is an example where we are putting this data in jsf file. After do any search in your application, you can just go to this page and you will see the total count for this situations.

<tr>
    <td>Cache</td>
    <!-- Hit -->
    <td></td>
    <!-- Miss -->
    <td></td>
    <! -- Conections -->
    <td></td>
</tr>


<tr>
    <td>Cache</td>
    <!-- Hit -->
    <td>${statistics.queryCacheHitCount}</td>
    <!-- Miss -->
    <td>${statistics.queryCacheMissCount}</td>
    <!-- Conections -->
    <td>${statistics.connectCount}</td>
</tr>

More information :
http://docs.jboss.org/hibernate/core/4.3/javadocs/org/hibernate/stat/Statistics.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s