Get access to all my video courses, 2 monthly Q&A calls, monthly coding challenges, a community of like-minded developers, and regular expert sessions.
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?
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.
11:23:21,398 DEBUG [org.hibernate.stat.internal.ConcurrentStatisticsImpl] - HHH000117: HQL: SELECT a FROM Author a WHERE a.id = :id, time: 22ms, rows: 1
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
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
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.