This is related to this question, which shows that default methods in Spring Data repositories do not hit the cache: Will default methods in Spring Data repositories hit caches on other methods?
I have this cached method:
@Cacheable("codeType-findIdByCode")
default Long findIdByCodeRequired(final String code) {
if (StringUtils.isBlank(code)) {
throw new DataCheckException(MSG_CODE_REQUIRED, getEntityMessageArgument());
}
return findIdByCode(code).orElseThrow(notFound(code));
}
And I want this default method to hit the cache:
default T getReferenceByCodeRequired(final String code) {
return getOne(findIdByCodeRequired(code));
}
Note that I tried this mechanism and it did not work:
default T getReferenceByCodeRequired(final String code) {
@SuppressWarnings("unchecked")
final CodeTypeRepository<T> codeTypeRepo = (CodeTypeRepository<T>) AopContext.currentProxy();
return getOne(codeTypeRepo.findIdByCodeRequired(code));
}
How can I get it to hit the cache without moving the default method out of the repository.
Reasons for keeping it in the repository: its a parent repository of a fair number of child repositories. A service method version of getReferenceByCodeRequired would need to take in the child repository itself in order to compose the two repository calls (findIdByCodeRequired and getOne)
Also, I don't want to put @Cacheable on the getReferenceByCodeRequired method as I'm trying to avoid caching entities.