Question
How can I see the actual SQL queries executed by Hibernate, including the values of the parameters?
Answer
When working with Hibernate, you may want to see the actual SQL queries that are sent to the database, including the parameter values that replace placeholders (like `?`). The default behavior of Hibernate is to show a parameterized SQL representation, but it is also possible to log the queries in a way that reveals the actual SQL being executed.
import org.hibernate.EmptyInterceptor;
public class SQLInterceptor extends EmptyInterceptor {
@Override
public void onPrepareStatement(String sql) {
System.out.println("SQL: " + sql);
super.onPrepareStatement(sql);
}
}
Causes
- Hibernate shows SQL queries with parameter placeholders but not the parameter values by default.
- The `show_sql` property merely logs the SQL statement structure without parameter values.
Solutions
- Use Hibernate's logging capability along with a simple interceptor or an additional library like `Hibernate's SQL Logging` capabilities to capture the executed SQL statements with bound parameter values.
- Consider using a debugger tool like Hibernate Profiler which displays detailed SQL execution information, including parameters.
Common Mistakes
Mistake: Setting the wrong logging level may not display the actual SQL queries.
Solution: Ensure you have set the logging level correctly to capture SQL details, often `DEBUG` is required for detailed logs.
Mistake: Not including necessary dependencies for logging libraries.
Solution: Check to make sure you have the logging framework (like log4j or slf4j) configured properly in your Hibernate project.
Helpers
- Hibernate SQL logging
- View actual SQL Hibernate
- Hibernate print SQL with parameters
- Hibernate query logging
- Show actual SQL Hibernate