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 use cases are slow and seem to perform too many queries. How can I count all queries executed within a Hibernate Session?
The easiest way to count all executed queries is to activate Hibernate’s statistics component. Hibernate then collects a lot of internal statistics and provides them as a log message and via the Statistics API. Collecting all these information takes some time, so do not use this in production!
Hibernate’s statistics component is deactivated by default. You can activate it by setting the hibernate.generate_statistics parameter to true. You can either do this by providing a system property with the same name or by setting the parameter in the persistence.xml file.
You have 2 options to access the statistics. Hibernate can write a subset with the most important information of each session to the log file or you can access them via the Statistics API. Let’s have a look at the log messages first. Hibernate writes a log message, similar the following one, at the end of each session. You can find the number of SQL statements and the time spent for their preparation and execution in line 4 and 5.
You can access the Statistics API via Hibernate’s SessionFactory. It provides a lot more information than the log output.
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.
If you want to learn more about finding and fixing Hibernate performance issue, you should have a look at the following posts:
- How to activate Hibernate Statistics to analyze performance issues
- Hibernate Logging Guide – Use the right config for development and production
- 7 Tips to boost your Hibernate performance
- Free Mini Course: How to find and fix n+1 select issues with Hibernate
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.