This guide explains how to enable and use caching in a Spring Boot app with SAP HANA Express. Follow and test directly.
1. Project Setup
Generate Spring Boot project from Spring Initializr:
- Dependencies: Spring Web, Spring Data JPA, Spring Cache
Install and add the SAP HANA JDBC driver (ngdbc.jar) into Maven local repo as explained in earlier guides.
2. Configure application.properties
spring.datasource.url=jdbc:sap://localhost:39015/?databaseName=HXE
spring.datasource.username=SYSTEM
spring.datasource.password=YourPassword
spring.datasource.driver-class-name=com.sap.db.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.HANARowStoreDialect
# cache config (simple in-memory)
spring.cache.type=simple
3. Enable Caching
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4. Create Entity
import jakarta.persistence.*;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// getters and setters
}
5. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
6. Service with Cache
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductRepository repo;
public ProductService(ProductRepository repo) {
this.repo = repo;
}
@Cacheable("products")
public Product getProduct(Long id) {
System.out.println("Fetching from DB...");
return repo.findById(id).orElseThrow();
}
}
7. Controller to Test
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) {
this.service = service;
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return service.getProduct(id);
}
}
8. Run and Test
Start the app:
mvn spring-boot:run
Test endpoint:
GET http://localhost:8080/products/1
- First call → fetches from DB.
- Second call → served from cache (no DB hit).
image quote pre code