Hibernate Tips: Count the executed queries in a Session

By Thorben Janssen

Query

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.

Question:

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?

Solution:

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.


Learn more:

If you want to learn more about finding and fixing Hibernate performance issue, you should have a look at the following posts:

 

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.

Get it now as a paperback, ebook or PDF.

Tags

Query


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Repl​​​​​y

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}