本文介绍了Spring JPA Hibernate查询缓存不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Spring Boot 1.4.1和spring-boot-starter-data-jpa
I use Spring Boot 1.4.1 AND spring-boot-starter-data-jpa
查询我的自定义方法(例如'findByName(String name)')时,它不会缓存.
When query my custom method like 'findByName(String name)' it's not cache.
但是当查询默认方法(例如'findOne(Interger id)')时,它就起作用了.
But when query default method like 'findOne(Interger id)' it's work.
application.properties:
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);
}
}
推荐答案
@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
Author findByName(String name);
}
应该做到这一点.(注意:因为您已经扩展了CrudRepository,所以不需要 @Repository
)
Should do the trick. (Note: the @Repository
is not needed because you already extend CrudRepository)
这篇关于Spring JPA Hibernate查询缓存不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!