This guide shows how to debug and analyze
JPA queries in
Spring Boot using the
H2 database and query logging.
1. Add Dependencies
In
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2
In
application.properties:
spring.datasource.url=jdbc:h2:mem:debugdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
3. Enable SQL Logging
Add to
application.properties:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
This logs SQL queries and parameter bindings.
4. Create Example Entity
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
private String name;
private String role;
}
5. Repository and Query
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByRole(String role);
}
6. Test the Query
@SpringBootTest
class EmployeeRepoTest {
@Autowired EmployeeRepository repo;
@Test
void testQuery() {
repo.save(new Employee(null, "Alice", "Dev"));
repo.findByRole("Dev");
}
}
Console logs will show the executed SQL and bound parameters.
7. Debug with H2 Console
Visit:
http://localhost:8080/h2-console
Use JDBC URL
jdbc:h2:mem:debugdb to run queries manually and verify results.
image quote pre code