This guide shows how to use the
H2 console in
Spring Boot to debug and inspect database content during development.
1. Add Dependency
In
pom.xml
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
2. Enable H2 Console
In
application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Now the console is available at:
http://localhost:8080/h2-console
3. Create a Sample Entity
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
}
4. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
5. Insert Data and Debug
Add a REST controller to insert users:
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserRepository repo;
public UserController(UserRepository repo) {
this.repo = repo;
}
@PostMapping
public User add(@RequestBody User user) {
return repo.save(user);
}
@GetMapping
public List<User> all() {
return repo.findAll();
}
}
6. Test with Console
- Start the app:
mvn spring-boot:run
- Open
/h2-console
.
- Use JDBC URL:
jdbc:h2:mem:testdb
.
- Run queries like:
SELECT * FROM USER;
This helps debug data directly from the DB.
image quote pre code