How to Detect Long Running Queries in Hibernate?

How to Detect Long Running Queries in Hibernate?

Most Java applications use Jakarta Persistence API (formerly Java Persistence API) to access databases. Hibernate is the most popular ORM framework for Java. It is a straightforward and easy-to-use implementation of JPA. However, its simplicity of usage often becomes mischievous to developers and leads to serious performance issues in Hibernate-based applications. How to detect such issues? The answer might lay in smart logging.

Logging Slow Queries

Hibernate supports logging queries that run longer than a specified amount of time in miliseconds. To configure this feature you need to use parameter hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS. This parameter can be very helpful in detecting bottlenecks in production systems without producing excessive number of logs.

Example:

hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=1000

Logging Queries with Parameters

When we tune or debug our applications, it often happens that we are interested not only in executed SQL/JPQL/HQL queries but also in parameters bound for a given query. Actually, that may be a crucial piece of information! Unfortunately, the widely-known show-sql logs only SQL queries without bound parameters.

In order to log queries along with bound parameters, you can use:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Leave a Reply

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