Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add cache feature in Spring Data JPA CRUDRepository

I want to add "Cacheable" annotation in findOne method, and evict the cache when delete or happen methods happened.

How can I do that ?

like image 864
virsir Avatar asked Dec 17 '12 12:12

virsir


People also ask

How does JPA implement cache in spring boot?

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.

How do I enable caching in spring?

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 .

Does JPA repository cache?

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.

Is CrudRepository a part of Spring data JPA?

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.


1 Answers

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);
}
like image 139
seven Avatar answered Oct 19 '22 09:10

seven