How to find slow SQL queries with Hibernate or JPA

Data persistence is one of the key factors when it comes to application performance. Therefore, it’s essential to keep track of the performance of your Database statements. First of all, it’s important to stress out that you can log statements emitted by Hibernate through one of the following methods:

1. Adding hibernate.show_sql property to your persistence.xml :

    <property name="hibernate.show_sql" value="true" />

2. Enabling logging of the following categories (using a file here):

3. By creating a Logging Handler for the org.hibernate.SQL namespace:

/subsystem=logging/periodic-rotating-file-handler=sql_handler:add(level=ALL, file={"path"=>"sql.log"}, append=true, autoflush=true, suffix=.yyyy-MM-dd,formatter="%d{yyyy-MM-dd HH:mm:ss,SSS}")

3. By enabling the spying of SQL statements:


Besides logging SQL statements, since Hibernate 5.4.5 a new property named can be used to display queries which are slower than a particular threshold (in ms.). This property can be added in your persistence.xml file as follows:

    <property name="" value="100"/>

To log slow queries to separate file, please configure logging like:

/subsystem=logging/periodic-rotating-file-handler=slow_sql_handler:add(level=INFO, file={"path"=>"slowsql.log"}, append=true, autoflush=true, suffix=.yyyy-MM-dd,formatter="%d{yyyy-MM-dd HH:mm:ss,SSS}")

As this feature requires Hibernate version 5.4.5, if your application server does not support that version yet, the recommended option is to bundle the latest Hibernate version in your application so that you will override the default version of it.

Found the article helpful? if so please follow us on Socials