Displaying Hibernate statistics in a Grails app

Hibernate offers a statistics object (org.hibernate.stat.Statistics) that can be used to monitor the behavior of Hibernate at runtime.
Statistics include connection count, max query execution time, cache hits/misses and many more.

To access the statistics, inject the sessionFactory into a controller and call the getStatistics() method on the sessionFactory:

class SystemController {
	SessionFactory sessionFactory

	def hibernateStatistics = {
		org.hibernate.stat.Statistics statistics = sessionFactory.statistics

		// TODO render the statistics
	}
}

To render the statistics I used Grails’ markup builder in the render() method to output HTML code:

render {
html {
	body {
		p {
			String[] statLines =
				(statistics.toString()-'Statistics').replaceAll('[\[\]]', '').split(',')
			statLines.each { stat ->
				span(stat)
				br()
			}
		}
	}
}
}

This should output something like this:
start time=1301467975890
sessions opened=168
sessions closed=167
transactions=325
successful transactions=156
optimistic lock failures=0
flushes=70
connections obtained=169
statements prepared=8629
statements closed=8629
second level cache puts=8074
second level cache hits=764
second level cache misses=0
[...]
queries executed to database=8597
query cache puts=386
query cache hits=2626
query cache misses=386
max query time=297

You should definitely secure this action (e.g. access should be granted to admins only).

The number of cache hits and misses (query cache hits, query cache misses, second level cache hits, second level cache misses) is what I found really helpful to check if my caches are set up correctly.

If you realize too many cache misses, check your caching configuration (see Caching Strategy in the Grails User Guide).

Short URL for this post: https://wp.me/p4nxik-uP
This entry was posted in Groovy and Grails and tagged , , , . Bookmark the permalink.

1 Response to Displaying Hibernate statistics in a Grails app

  1. Avatar Mike Hugo says:

    You can also use the Hibernate Stats plugin to get similar output, and even to expose an MBean. See http://grails.org/plugin/hibernate-stats

Leave a Reply