Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
Some of my queries seem to be slow. Can Hibernate measure and log the execution time of a query?
Don’t want to read? You can watch it here!
Hibernate’s statistics component collects a lot of internal statistics and writes some of them to the log file. One of them is the execution time for each query.
You can activate these messages in 2 steps. You need to:
- Activate the statistics
- Configure the log level accordingly
Let’s activate Hibernate’s statistics component first. They are deactivated by default because collecting all these information slows down your application. So please, don’t use it in production!
The only thing you have to do is to set the property hibernate.generate_statistics to true. You can do that programmatically, with a system property or in the persistence.xml file. I recommend using the system property because you can change it without changing your application.
If you want to configure it in the persistence.xml file, you can see an example configuration in the following code snippet.
<persistence> <persistence-unit name="my-persistence-unit"> ... <properties> <property name="hibernate.generate_statistics" value="true" /> ... </properties> </persistence-unit> </persistence>
After you’ve activated the statistics component, you need to set the log level for the org.hibernate.stat category to DEBUG. Hibernate then writes a log message for each query with the executed HQL statement, the execution time and the retrieved number of rows.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
Choosing the right logging configurations for development and production is an important but often ignored topic. It helps you to find bugs and performance issues during development and avoids any overhead when you need the best performance.
I get into more details about it and show you my preferred configurations in Hibernate Logging Guide – Use the right configuration for development and production.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.