Home > Software engineering >  Can Hibernate SessionFactory work with no 3rd part caching systems (Redis, HazelCast, etc)?
Can Hibernate SessionFactory work with no 3rd part caching systems (Redis, HazelCast, etc)?

Time:06-06

I've read some articles and questions about Hibernate caching, but I still don't get the concept about SessionFactory caching: is it possible to have and use application L2 cache using SessionFactory without any 3d part systems like Redis or HazelCast? If it's possible, what're the main differences between using "plane" SessionFactory and SessionFactory together with other caching systems?

CodePudding user response:

Hibernate second-level caching is designed to be unaware of the actual cache provider used. Hibernate only needs to be provided with an implementation of the org.hibernate.cache.spi.RegionFactory interface which encapsulates all details specific to actual cache providers. Basically, it acts as a bridge between Hibernate and cache providers.

You can use Ehcache as a cache provider, which is a mature and widely used cache. You can pick any other provider of course, as long as there is an implementation of a RegionFactory for it.

So If you want to enable second level cache for your hibernate session factory then you have to use third party cache provider like Ehcache.

What changes needed for L2 cache

  1. Property File Change -

With the following two properties we tell Hibernate that L2 caching is enabled and we give it the name of the region factory class:

hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
  1. Entity level change -

In order to make an entity eligible for second-level caching, we annotate it with Hibernate specific @org.hibernate.annotations.Cache annotation and specify a cache concurrency strategy.

@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Foo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private long id;

    @Column(name = "NAME")
    private String name;
    
    // getters and setters
}
  • Related