Sunday, 1 September 2019

How to configure Spring Boot to show Hibernate SQL Query in logs?

🚀 Love Java Development?

Subscribe to Ram N Java for the best Spring Boot tutorials and Java tips!

SUBSCRIBE NOW

Configuring Spring Boot for Hibernate Logs

When developing a Spring Boot application that uses Hibernate for database operations, seeing the actual SQL queries being executed is crucial for debugging and optimization. This guide will show you the easiest way to enable and configure these logs.

Why Enable Hibernate Logs?

By default, Spring Boot stays quiet about what's happening between your application and the database. Enabling logs allows you to:

  • Verify that your JPA queries are generating the SQL you expect.
  • Identify "N+1" select problems that can slow down your app.
  • Debug why a specific database record isn't being updated correctly.

The Quick Configuration

To see the SQL in your console, you simply need to add a few lines to your application.properties file:

# Show SQL in the console
spring.jpa.show-sql=true

# Format the SQL to make it readable
spring.jpa.properties.hibernate.format_sql=true

# Show the values of parameters (?) in the query
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Summary of Key Settings

show-sql: This is the most basic setting. Setting it to true prints the query to the standard output.

format_sql: Without this, your SQL will appear as one long, hard-to-read line. Setting this to true beautifies the output with proper indentation.

Logging Levels: If you need even more detail, adjusting the logging levels for the org.hibernate package will give you insights into transaction management and internal Hibernate states.


Check Out More Tutorials From Ram N Java:

1 comment:

  1. Configuring Spring Boot to display Hibernate SQL queries is essential for debugging and optimizing performance. For complex projects, businesses can Hire Backend Developers to ensure accurate logging and efficient database management in their applications.

    ReplyDelete