πŸš€ Database Caching In Spring Boot?

Database Caching stores frequently accessed data in memory (RAM), so your app doesn’t hit the database every time.

🎯 Result: Faster performance + reduced DB load


βœ… When to Use It?

  • Same data is read again and again (e.g., user info, product list)
  • Performance is critical (e.g., high-traffic APIs)

πŸ› οΈ How to Enable Caching in Spring Boot

βœ… Step 1: Add Starter Dependency

In pom.xml:

<dependency>
Β  <groupId>org.springframework.boot</groupId>
Β  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

βœ… Step 2: Enable Caching in Main Class

@SpringBootApplication
@EnableCaching
public class MyApp {
Β  Β  public static void main(String[] args) {
Β  Β  Β  Β  SpringApplication.run(MyApp.class, args);
Β  Β  }
}

βœ… Step 3: Use @Cacheable in Your Service

Β 

@Service
public class StudentService {

Β  Β  @Autowired
Β  Β  private StudentRepository repo;

Β  Β  @Cacheable("students")
Β  Β  public Student getStudentById(Long id) {
Β  Β  Β  Β  System.out.println("Fetching from DB...");
Β  Β  Β  Β  return repo.findById(id).orElse(null);
Β  Β  }
}

πŸ“Œ Now, the first call will fetch from the DB and store it in cache.
Next time? Fetched from memory – faster!


βš™οΈ How It Works

  • @Cacheable β†’ stores method result
  • @CacheEvict β†’ removes entry from cache
  • @CachePut β†’ updates entry in cache

🧠 What Cache is Used?

By default: Simple in-memory (ConcurrentMap)

For production: Use EhCache, Redis, or Caffeine


πŸ—‚ application.properties (optional settings)

spring.cache.type=simple Β  # or redis, caffeine, etc.

πŸ§ͺ Example Output:

GET /students/101
β†’ Fetching from DB...

GET /students/101 (again)
β†’ (No DB call – data returned from cache)

Β 

Back to blog

Leave a comment