Spring JPA Hibernate查询缓存不起作用

时间:2016-10-25 18:14:24

标签: hibernate spring-data-jpa

我使用Spring Boot 1.4.1和spring-boot-starter-data-jpa

查询我的自定义方法时,例如' findByName(String name)'它没有缓存。

但是当查询默认方法如' findOne(Interger id)'它的工作。

application.properties:

spring.jpa.properties.hibernate.cache.use_query_cache=true

存储库:

@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
    Author findByName(String name);
}

试验:

public class RepositoryTests {
    @Autowired
    private AuthorRepository authorRepository;

    @Test
    @Transactional
    public void test() {
        authorRepository.save(new Author("admin"));

        // ***Not work. query **5** times.
        Author author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");

        // ***It's work. query **1** times.
        Author author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
    }
}

1 个答案:

答案 0 :(得分:2)

@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
    @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
    Author findByName(String name);
}

应该做的伎俩。 (注意:不需要@Repository,因为您已经扩展了CrudRepository)