This guide shows how to combine H2 as a database and Redis as a cache in Spring Boot for faster performance.
1. Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2. Configure H2 and Redis
spring.datasource.url=jdbc:h2:mem:cachedb
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.redis.host=localhost
spring.redis.port=6379
spring.cache.type=redis
3. Enable Caching
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4. Create Entity
@Entity
public class Product {
@Id @GeneratedValue
private Long id;
private String name;
private double price;
}
5. Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}
6. Service with Cache
@Service
public class ProductService {
private final ProductRepository repo;
public ProductService(ProductRepository repo) {
this.repo = repo;
}
@Cacheable("products")
public Product findById(Long id) {
return repo.findById(id).orElse(null);
}
@CacheEvict(value = "products", allEntries = true)
public Product save(Product product) {
return repo.save(product);
}
}
7. Test the Cache
- Call
findById(1) → hits H2 database.
- Call again → returns instantly from Redis cache.
- Save new data → cache is cleared automatically.
image quote pre code