5

I am trying to create Repository with L2 cache with minimal setting. My database is postgresql.

I start with spring-boot-sample-data-jpa-archetype project using maven. I have removed the HSQL and create a DataSource bean to connect to postgresql. Also use ddl to create schema and imported the initial script data.

I have also added the @Cacheable to my entities. Then I use unit test to query an entity 10 times using repository. It took 1~49ms. So that leaves me two questions.

  1. Does repository benefits from L1 cache? how do I know if I am hitting the cache or data source?
  2. How to enable L2 cache? does Spring data has its own implementation?
Maxi Wu
  • 1,274
  • 3
  • 20
  • 38

2 Answers2

13

After some testing and the help from @dunni, I will answer my own question. Spring uses Hibernate as an implementation of JPA. Spring data provides some wrapper over Hibernate. Also need to choose a caching implementation.

To enable L2 cache, add these properties to your project.

  1. spring.jpa.properties.hibernate.cache.use_second_level_cache=true
  2. spring.jpa.properties.hibernate.cache.use_query_cache=true
  3. spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

also add these dependencies: hibernate-ehcache

Then, add @Cacheable(true) to your entity model class. Extends a repository interface, Spring will generate the implementation using naming convention. For example

@QueryHints({@QueryHint(name="org.hibernate.cacheable", value="true")})
Entity findByName(String name)

You can also implement the interface. But that will require adding a hint to your query object to activate L2 cache.

query.setHint("org.hibernate.cacheable", true);

To verify the cache is working, you can use the following properties to see if the SQL has been executed.

  1. spring.jpa.show-sql=true
  2. spring.jpa.properties.hibernate.format_sql=true
bakoyaro
  • 2,550
  • 3
  • 36
  • 63
Maxi Wu
  • 1,274
  • 3
  • 20
  • 38
0

after reading your comment and checking my code, my code started working. Also, with adding spring.jpa.properties.hibernate.generate_statistics=true i can see my db calls more detailed. demo project link

Log of calling same endpoint twice

Thank you

Kambaa
  • 467
  • 3
  • 8