Search code examples
javahibernatecachinghibernate-criteriahibernate-cache

hibernate query by example caching


I have the following Mapped entity:

@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "eKey-field-1", "eKey-field-2", "eKey-field-3" }))
class EntityMapped {
    @Id
    @GeneratedValue...
    Long Id;

    @Embedded
    EntityKeyMapped eKey;

There are no updates and no deletes. New records are added if there is no security for the given eKey.

The select queries are very simple, but up to 1+ Mln queries executed in parallel per day (+sometimes new records are added). So I think to cache it somehow.

Within the Dao I see something like:

return (EntityMapped) getSession().createCriteria(EntityMapped.class).add(Example.create(example)).uniqueResult();

I am thinking of the best way to cache this requests. Atm I consider :

return (EntityMapped) getSession().createCriteria(EntityMapped.class).add(Example.create(example)).setCacheable(true).uniqueResult();

But maybe for this case there is a better (easier) way to cache?


Solution

  • You are enabling caching in proper way. This is the way that Hibernate team has designed.

    If you are using spring (or com.googlecode.ehcache.annotations, etc) you can enable caching by putting annotation on the method. But then this will be outside of hibernate.

    When using pure hibernate, your solution is proper.

    One thing to remember is that you can enable caching and setup proper region to use:

    return (SecurityMapped) getSession()
      .createCriteria(SecurityMapped.class)
      .add(Example.create(example))
      .setCacheable(true)
      .setCacheRegion("myregion")   // here you can choose region
      .uniqueResult();
    

    Then in yor cache provider configuration file you can configure different regions.

    For example in EhCache configuration you can setup "myregion" this way:

    <ehcache ...>
    
        <cache name="myregion" 
               maxElementsInMemory="1000" 
               eternal="false" 
               timeToIdleSeconds="3600" 
               timeToLiveSeconds="7200" 
               overflowToDisk="false" 
               memoryStoreEvictionPolicy="LFU"/>
    
    </ehcache>