Finding performance issues with Hibernate statistics

Most of the time, we face slow responses on the production system, while our local or test system works just fine. Most of these cases are because of slow database queries. In a local instance, we don't know the exact volume of requests and volume of data that we have in production. So, how do we find out which query is causing the problem, without adding logs to our application code? The answer is the Hibernate generate_statistics configuration.

We need to set the Hibernate property generate_statistics to true, as this property is false by default. This property impacts the overall performance, as it logs all database activities. So, enable this property only when you want to analyze slow queries. This property will generate summarized multiline logs, showing how much overall time is spent on database interaction.

If we want to log the execution of each query, we need to enable org.hibernate.stat to the DEBUG level in log configuration; similarly, if we want to log SQL queries (with times), we need to enable org.hibernate.SQL to the DEBUG level.

The following is an example of a printed log:

Hibernate generate_statistics logs

An overall statistics information log shows the number of JDBC connections used, statements, caches, and performed flushes. We always need to check the number of statements first to see if there is an n + 1 issue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset