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.
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.
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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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
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.