Nick Div
Nick Div

Reputation: 5628

EhCache configuration with annotations - Hibernate

Is there a way to configure EHcache using annotations.

I have a Spring/Hibernate project that has Cache enabled. Currently I am using ehcache.xml to define the configuration of how entities will be cached.

This is what my ehcache.xml looks like:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir/ehcache"/>

    <defaultCache
       .
       .
       .
    </defaultCache>

    <cache name="exmaple.model.User" maxEntriesLocalHeap="1000" eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="300">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

I was wondering if this was possible to do the same with annotations on top of @Entity instead of using this xml file.

Upvotes: 3

Views: 1496

Answers (1)

Henri
Henri

Reputation: 5721

There are two parts. One is Spring Cache and Hibernate. They both provide annotations to tell that a methods or an entity should be cached.

An example is @Cacheable from Spring Cache.

Then, you have the ehcache.xml. This is to configure caches themselves. It won't be by annotations. But it can be programmatically. Ehcache 3 makes it easy using builders. You will see an example here. This sample also use Spring Cache and Hibernate second level caching.

Ehcache 2 (which you are using) has no builder. You need to call CacheManager.newInstance(Configuration) and put whatever configuration you want in it. Sadly, I don't have an example at hand.

Upvotes: 2

Related Questions