Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring repository : @CacheEvict on save methods

I'd like to add a @CacheEvict() decorator to my save / saveAll methods from my repository.

I've tried to override the methods by using custom implementation by reading this thread but I don't want to rewrite the method implementation, just call the default one with more behavior. None of the solutions provided work well for my case, or require far too much customization.

@Transactional(readOnly = true)
@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {

   // This is working fine as its a custom query method
   @Cacheable(value = "ENTITIES")
   MyEntity findByCategory(String category);

   // This isn't working as it won't implement the function correctly. Save don't work anymore here.
   @CacheEvict(value = "ENTITIES", key = "#entity.hashCode()")
   <S extends MyEntity> S save(S entity);

}

I could call the cache eviction manually from the method's body, but I can't just override the save() method and call the super.save() since I only use interfaces and let Spring generate the implementation.

Any advices?

like image 425
Kapcash Avatar asked Oct 22 '25 09:10

Kapcash


1 Answers

Found. It was dummy. Just removed the @Transactional(readOnly = true). It was preventing the save from working.

So just overriding the signature of the method is enough to add some decorators without caring about the implementation.

@Override
@CacheEvict(value = "ENTITIES", key = "#p0.getKeyWhateverItIs()")
<S extends Feature> S save(S entity);

And yes, the key value was wrong as well, but not implicated in the non-working save method.

like image 84
Kapcash Avatar answered Oct 24 '25 23:10

Kapcash