I use Spring Boot 1.4.1 AND spring-boot-starter-data-jpa
When query my custom method like 'findByName(String name)' it's not cache.
But when query default method like 'findOne(Interger id)' it's work.
application.properties:
spring.jpa.properties.hibernate.cache.use_query_cache=true
Repository:
@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
Author findByName(String name);
}
Tests:
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);
}
}
The Hibernate second level cache is an application level cache for storing entity data. The query cache is a separate cache that stores query results only. The two caches really go together, as there are not many cases where we would like to use one without the other.
To use the query cache, you must first activate it using the hibernate. cache. use_query_cache="true" property in the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to hold the query and identifier sets.
@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
Author findByName(String name);
}
Should do the trick. (Note: the @Repository
is not needed because you already extend CrudRepository)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With