Country đã có @Cacheable và @Cache(usage = CacheConcurrencyStrategy.READ_WRITE), second-level cache hoạt động. Thế nhưng log SQL cho thấy mỗi lần gọi countryRepository.findByCode("VN") (derived query) vẫn có một câu SELECT. Vì sao?
Xem đáp án và giải thích
Entity cache là một map id → dữ liệu entity. findById, em.find, load @ManyToOne dùng được nó, còn mọi JPQL/Criteria/derived query phải chạy SQL để biết những id nào khớp. Muốn cache tra cứu theo code, bật query cache cho đúng query đó, hoặc cache ở tầng service (Spring @Cacheable) với key là code.