In this post, we will explore how to enable logging of SQL statements in a Spring Boot application.

Spring Boot supports various data access technologies, such as JDBC, JPA, Hibernate, etc, which allow us to interact with various databases and execute SQL queries to manipulate data. Sometimes we may need to see the SQL statements that are generated and executed by them, for debugging, performance tuning, or auditing purposes. For example, we may want to see how the SQL queries are constructed, what parameters are passed, how long they take to execute, and what results they return.

1. Logging SQL Statements with Spring Data JPA and Hibernate

To enable logging of SQL statements with Spring Data JPA and Hibernate, we can use the following properties in the application.properties or application.yml file:

 
The spring.jpa.show-sql property enables or disables the logging of SQL statements to the standard output. The spring.jpa.properties.hibernate.format_sql property enables or disables the formatting of SQL statements for better readability. The logging.level.org.hibernate.type property sets the logging level for the org.hibernate.type package, which is responsible for logging the parameters of prepared statements. By setting these properties, we can see the SQL statements and their parameters in the application logs.

2. Logging SQL Statements with Spring JDBC and JdbcTemplate

To enable logging of SQL statements with Spring JDBC and JdbcTemplate, we can use the following properties in the application.properties or application.yml file:

 
The logging.level.org.springframework.jdbc.core.JdbcTemplate property sets the logging level for the org.springframework.jdbc.core.JdbcTemplate class, which is responsible for logging the SQL statements. The logging.level.org.springframework.jdbc.core.StatementCreatorUtils property sets the logging level for the org.springframework.jdbc.core.StatementCreatorUtils class, which is responsible for logging the parameters of prepared statements. By setting these properties, we can see the SQL statements and their parameters in the application logs.

That’s all about enabling logging of SQL statements in a Spring Boot.