This guide explains how to integrate
H2 database with
Spring Boot microservices for lightweight development and testing.
1. Add Dependencies
In each microservice
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 of a microservice:
spring.datasource.url=jdbc:h2:mem:service_db
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
This sets up an in-memory DB per microservice.
3. Create an Entity
@Entity
public class Order {
@Id @GeneratedValue
private Long id;
private String product;
private int quantity;
}
4. Repository
public interface OrderRepository extends JpaRepository<Order, Long> {}
5. REST Controller
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired private OrderRepository repo;
@PostMapping
public Order save(@RequestBody Order order) {
return repo.save(order);
}
@GetMapping
public List<Order> findAll() {
return repo.findAll();
}
}
6. Running Multiple Microservices
Each service can have its own H2 DB.
For example:
OrderService → jdbc:h2:mem:order_db
CustomerService → jdbc:h2:mem:customer_db
They run independently and are isolated for testing.
image quote pre code