Optimization is not much use without monitoring and access to performance numbers. Hibernate provides a full range of figures about its internal operations. Statistics in Hibernate are available per SessionFactory
.
You can access SessionFactory
metrics in two ways. Your first option is to call sessionFactory.getStatistics()
and read or display the Statistics
yourself.
Hibernate can also use JMX to publish metrics if you enable the StatisticsService
MBean. You may enable a single MBean for all your SessionFactory
or one per factory. See the following code for minimalistic configuration examples:
// MBean service registration for a specific SessionFactory
Hashtable tb = new Hashtable();
tb.put("type", "statistics");
tb.put("sessionFactory", "myFinancialApp");
ObjectName on = new ObjectName("hibernate", tb); // MBean object name
StatisticsService stats = new StatisticsService(); // MBean implementation
stats.setSessionFactory(sessionFactory); // Bind the stats to a SessionFactory
server.registerMBean(stats, on); // Register the Mbean on the server
// MBean service registration for all SessionFactory's
Hashtable tb = new Hashtable();
tb.put("type", "statistics");
tb.put("sessionFactory", "all");
ObjectName on = new ObjectName("hibernate", tb); // MBean object name
StatisticsService stats = new StatisticsService(); // MBean implementation
server.registerMBean(stats, on); // Register the MBean on the server
TODO: This doesn't make sense: In the first case, we retrieve and use the MBean directly. In the second one, we must give the JNDI name in which the session factory is held before using it. Use hibernateStatsBean.setSessionFactoryJNDIName("my/JNDI/Name")
You can (de)activate the monitoring for a SessionFactory
Statistics can be reset programatically using the clear()
method. A summary can be sent to a logger (info level) using the logSummary()
method.