Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Hibernate query cache doesn't work

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);
    }
}
like image 965
Alex Avatar asked Oct 25 '16 18:10

Alex


People also ask

Are Hibernate queries cached?

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.

How to use Hibernate caching?

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.


1 Answers

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

like image 87
Y.M. Avatar answered Sep 28 '22 18:09

Y.M.