📜  spring boot show sql - Java (1)

📅  最后修改于: 2023-12-03 14:47:32.816000             🧑  作者: Mango

Spring Boot Show SQL - Java

Introduction

This tutorial explains how to configure and use the spring-boot-starter-data-jpa dependency in a Spring Boot application to show SQL statements.

By default, Spring Boot uses an embedded database (H2) and hides the SQL statements generated by JPA queries. However, it is sometimes necessary to view the actual SQL queries for debugging or optimization purposes. This tutorial will guide you on how to enable SQL logging in a Spring Boot application, which allows you to see the generated SQL statements.

Prerequisites
  • Basic knowledge of Spring Boot and Java programming
  • Java Development Kit (JDK) installed
  • Maven or Gradle installed
Steps
Step 1: Create a Spring Boot Project
  1. Use your preferred IDE or the Spring Initialzr website (https://start.spring.io/) to create a new Spring Boot project.
  2. Add the spring-boot-starter-data-jpa and your preferred database driver as dependencies in your pom.xml (Maven) or build.gradle (Gradle) file.
Step 2: Configure SQL Logging

By default, Spring Boot logs the SQL statements at the DEBUG level. To enable SQL logging in your application, you can modify the application.properties or application.yml file with the following configuration:

application.properties

spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=debug

application.yml

spring:
  jpa:
    show-sql: true
logging:
  level:
    org.hibernate.SQL: debug

This configuration enables SQL logging for Hibernate, which is the default JPA provider used by Spring Boot.

Step 3: Run the Application

Run your Spring Boot application using the following command:

mvn spring-boot:run
Step 4: View the SQL Statements

Check the console output or log file of your application. You should now see the SQL statements generated by JPA queries.

Conclusion

Congratulations! You have successfully configured your Spring Boot application to show SQL statements. This feature can be useful for troubleshooting, optimizing database queries, and improving the performance of your application. Feel free to modify the logging level or explore other logging frameworks to suit your needs.

For more advanced configurations, such as using an external database or customizing the logging format, refer to the official Spring Boot documentation.

Happy coding!