Hibernate Tips: Use query comments to identify a query

By Thorben Janssen

Criteria API, Jpql, 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:

My application performs a lot of similar queries and I need to find the output of a specific query in my log file. Is there any way to identify a specific query in the log output.

Solution:

Hibernate can add a comment when it generates an SQL statement for a JPQL or Criteria query or executes a native SQL query. You can see it in your application log file, when you activate SQL statement logging and in your database logs.

You need to activate SQL comments by setting the configuration parameter hibernate.use_sql_comments to true. The following code snippet shows an example configuration in the persistence.xml file.

The generated comments are often not useful to find a specific query. You should, therefore, use the org.hibernate.comment query hint to provide your own comment.

I use it in the following example to set the SQL comment for my query to “This is my comment”.

Hibernate adds this comment to the generated SQL statement and writes it to the log file.

Learn More:

I got into a lot more details about Hibernate’s logging capabilities in Hibernate Logging Guide – Use the right config for development and production.

Hibernate and JPA support a lot more hints than I showed you in this post. I summarized the most interesting ones in 11 JPA and Hibernate query hints every developer should know.

 

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

Criteria API, Jpql, 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.

  1. Hello,
    Thanks for sharing such informative and helpful blog post and you are doing a good job so keep posting such amazing articles

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