How to set and retrieve Hibernate statistics by JMX

Environment: Hibernate 3.x, Spring 2.x and Tomcat 5.x

Hibernate part: Into the hibernate.cfg.xml file add the property “generate_statistics” and set property value to “true

<property name="hibernate.generate_statistics">true</property>

Spring part: In the xml file containing the declaration of the Hibernate Session Factory add the following beans:

<bean id="hibernateStats" class="org.hibernate.jmx.StatisticsService">
<property name="sessionFactory">
<ref bean="hb3SessionFactory"/>
<!--put here the reference to the bean containing the Hibernate Session Factory -->

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<entry key="bean:name=hibernateStatsMBean">
<ref bean="hibernateStats"/>
<property name="assembler">
<bean   class="org.springframework.jmx.export.assembler.MethodNameBasedMBeanInfoAssembler">
<property name="methodMappings">
<prop key="bean:name=hibernateStatsMBean">

Tomcat part: Add the following system properties at the execution of Tomcat:

Start the Tomcat server and use your application.

The result: Start up the jconsole application, go the “MBeans” tab and click on the “hibernateStatsMBean” tree node. You should see something like this: