Spring Data存储库中的默认方法是否会影响同一存储库中其他方法的缓存?
例如,调用这个方法:
default Long findIdByCodeRequired(final String code) {
if (StringUtils.isBlank(code)) {
throw new DataCheckException(MSG_CODE_REQUIRED, getEntityMessageArgument());
}
return findIdByCode(code).orElseThrow(notFound(code));
}
在此方法上命中缓存?
@Cacheable("codeType-findIdByCode")
@Query("select c from #{#entityName} c " //
+ "where c.code = :code")
Optional<Long> findIdByCode(String code);
或者默认方法不通过缓存工作所需的代理吗?
所以答案是"不,存储库中的默认方法不会在其他方法上缓存">
@Test
@Transactional
public void testContactTypeCaching() {
System.out.println("first call to findIdByCode");
contactTypeRepo.findIdByCode("MOBILE");
System.out.println("second call to findIdByCode");
contactTypeRepo.findIdByCode("MOBILE");
System.out.println("third call to findIdByCode");
contactTypeRepo.findIdByCode("MOBILE");
System.out.println("first call to getReferenceByCodeRequired");
contactTypeRepo.getReferenceByCodeRequired("MOBILE");
System.out.println("second call to getReferenceByCodeRequired");
contactTypeRepo.getReferenceByCodeRequired("MOBILE");
System.out.println("third call to getReferenceByCodeRequired");
contactTypeRepo.getReferenceByCodeRequired("MOBILE");
}
输出:
first call to findIdByCode
Hibernate:
select
contacttyp0_.ct_id as col_0_0_
from
contact_types contacttyp0_
where
contacttyp0_.code=?
second call to findIdByCode
third call to findIdByCode
first call to getReferenceByCodeRequired
Hibernate:
select
contacttyp0_.ct_id as col_0_0_
from
contact_types contacttyp0_
where
contacttyp0_.code=?
second call to getReferenceByCodeRequired
Hibernate:
select
contacttyp0_.ct_id as col_0_0_
from
contact_types contacttyp0_
where
contacttyp0_.code=?
third call to getReferenceByCodeRequired
Hibernate:
select
contacttyp0_.ct_id as col_0_0_
from
contact_types contacttyp0_
where
contacttyp0_.code=?