java—spring数据仓库中的默认方法会命中其他方法的缓存吗?

hgqdbh6s  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(293)

spring数据存储库中的默认方法是否会命中同一存储库中其他方法的缓存?
例如,调用此方法:

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);

或者默认方法不通过缓存工作所需的代理吗?

wsxa1bj1

wsxa1bj11#

所以答案是“不,存储库中的默认方法不会命中其他方法的缓存”

@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=?

相关问题