I want to add "Cacheable" annotation in findOne method, and evict the cache when delete or happen methods happened.
How can I do that ?
The simplest way to enable caching behavior for a method is to mark it with @Cacheable and parameterize it with the name of the cache where the results would be stored. It provides a parameter called allEntries that evicts all entries rather than one entry based on the key.
To enable the Spring Boot caching feature, you need to add the @EnableCaching annotation to any of your classes annotated with @Configuration or to the boot application class annotated with @SpringBootApplication .
It caches entities that are explicitly declared to be cacheable. Upon retrieval of a cacheable entity, the JPA runtime first looks for this entity in the persistence context, then in the entity cache, and finally in the database.
CrudRepository and JPA repository both are the interface of the spring data repository library. Spring data repository reduces the boilerplate code by providing some predefined finders to access the data layer for various persistence layers. JPA repository extends CrudRepository and PagingAndSorting repository.
virsir, there is one more way if you use Spring Data JPA (using just interfaces). Here what I have done, genereic dao for similar structured entities:
public interface CachingDao<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
@Cacheable(value = "myCache")
T findOne(ID id);
@Cacheable(value = "myCache")
List<T> findAll();
@Cacheable(value = "myCache")
Page<T> findAll(Pageable pageable);
....
@CacheEvict(value = "myCache", allEntries = true)
<S extends T> S save(S entity);
....
@CacheEvict(value = "myCache", allEntries = true)
void delete(ID id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With