Video in progress

This code puts a Hibernate entity into Spring Cache. What problems come up, and how would you rewrite it?

@Service
public class CatalogService {

    @Cacheable("products")
    @Transactional(readOnly = true)
    public Product get(Long id) {
        return repo.findById(id).orElseThrow();
    }

    @Transactional
    public void applyDiscount(Long id, int percent) {
        Product p = get(id);
        p.setPrice(p.getPrice().multiply(BigDecimal.valueOf(100 - percent)).divide(BigDecimal.valueOf(100)));
    }
}

What lands in the cache is a managed entity: on later requests it is detached, its lazy associations throw LazyInitializationException, one object ends up shared across threads, and if anyone modifies it, everyone is affected. The cache should hold an immutable DTO (a record), not an entity.

📖 Answer

Several problems are stacked on top of each other in this code.

  1. The object in the cache is the Product loaded in that first transaction. When the transaction ends, it is detached. A second request takes it from the cache and calls product.getCategory().getName(): LazyInitializationException, but only when the cache is warm. It's a bug you never see locally and that shows up randomly on prod.

  2. A local cache (Caffeine) stores the object itself. If one thread modifies it, the others see the changed price too, even though nothing changed in the database. An entity is not thread-safe.

  3. get(id) inside applyDiscount is a call through this, so the @Cacheable proxy does not kick in, which means there is no caching there at all. But if it is called from somewhere else, the detached object comes back from the cache, and modifying it is not saved to the database. The behavior depends on which path the call came through.

  4. The price changed but the cache still holds the old value: there is no @CacheEvict.

  5. In a distributed cache like Redis, the entity gets serialized: the Hibernate proxy and PersistentBag end up in serialization and produce an error or a lot of useless data.

The rewritten version:

public record ProductView(Long id, String name, BigDecimal price, String category) {}

@Cacheable("products")
@Transactional(readOnly = true)
public ProductView view(Long id) {
    return repo.findView(id).orElseThrow();       // DTO projection
}

@Transactional
@CacheEvict(cacheNames = "products", key = "#id")
public void applyDiscount(Long id, int percent) {
    Product p = repo.findById(id).orElseThrow();   // always a managed entity
    p.applyDiscount(percent);
}

The rule is simple: only immutable, serializable DTOs go into the application cache. If you need caching at the entity level, that is the job of Hibernate's L2 cache: it stores the entity's values, not the entity itself, and assembles a fresh object for each session. Also don't forget that the evict should happen after the commit, otherwise a parallel read can put the old value back into the cache.