As in-memory data-grid Hazelcast is well suited for a distributed cache. In this post I will show you how to setup Hazelcast as a second level cache for Hibernate. For further information you can check the documentation or download my sample project from Github.
The important dependencies for the Hazelcast part are hazelcast and hazelcast-hibernate4. As the current Hazelcast version does not support Hibernate 4 you need an additional implementation for that.
<dependency> <groupid>com.hazelcast</groupid> <artifactid>hazelcast</artifactid> <version>3.0.2</version> </dependency> <dependency> <groupid>com.hazelcast</groupid> <artifactid>hazelcast-hibernate4</artifactid> <version>3.0.2</version> </dependency>
In your persistence.xml you add the following lines to activate the second level cache and configure Hibernate to use Hazelcast for it.
<property name="hibernate.cache.use_second_level_cache" value="true" /> <property name="hibernate.cache.use_minimal_puts" value="true" /> <property name="hibernate.cache.hazelcast.use_lite_member" value="true" /> <property name="hibernate.cache.region.factory_class" value="com.hazelcast.hibernate.HazelcastCacheRegionFactory" />
In Hibernate 4 you now can annotate your entity with
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
to enable caching for that particular class. There are some configuration you can do using the hazelcast.xml. Check the sample project to see the complete setup with some tests to run.
See also:
- Hazelcast website
- Hazelcast documentation
- hazelcast-hibernate4 on Github
- DZone: All About Hibernate Second Level Cache