How to log the class and method that generated a given SQL query with JPA and Hibernate


#1

Hello,

I have in my project Hibernate 5.0.11. configurated with

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

I’m interested in knowing if its possible, to see on the log of queries shown by Hibernate
the class and the method that “generated” the query.

I’m also not sure if this is a feature that should be done by the Hibernate.

Tássio Miranda


#2

I’m interested in knowing if its possible, to see on the log of queries shown by Hibernate
the class and the method that “generated” the query.

I suppose you are interested in the class and method of your service or data access layer, which is not something Hibernate can help you with since your classes are higher up the stack.

However, you can use datasource-proxy to customize the logger and append the info you want by using StackWalker to identify your classes/methods that generated that executing query.

Also, check out the MDC support of the underlying logging framework you are using. It can also help you append the info you are interested via ThreadContext variables. Check out this article for more details.