Syed
Syed

Reputation: 2607

Fetch latest data using Ehcache in Hibernate using Java

I'm wondering why Ehcache is fetching the latest data whenever I change something in my DB. As per the documentation of Ehcache, it should fetch only after a certain time interval. Am I correct?

Here is my ehcache.xml

<?xml version="1.0"?>  
<ehcache>  
 <defaultCache   
  maxElementsInMemory="100"   
  eternal="false"   
  timeToIdleSeconds="120"   
  timeToLiveSeconds="200" />  

  <cache name="com.sch.Employee"   
  maxElementsInMemory="100"   
  eternal="false"   
  timeToIdleSeconds="5"   
  timeToLiveSeconds="200" />  
 </ehcache>  

My entity class

package com.sch;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Entity
public class Employee {

    @Id
    private int id;
    private String name;


    public Employee() {
    }

    public Employee(String name, float salary) {
        super();
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}

Is my understanding correct? If not, what's exactly running behind the scenes of EHcache?

Upvotes: 1

Views: 167

Answers (1)

Vinay Veluri
Vinay Veluri

Reputation: 6855

TTI and TTL are the ones which decide the eviction process.

timeToIdleSeconds – The maximum number of seconds an element can exist in the cache without being accessed. The element expires at this limit and will no longer be returned from the cache. The default value is 0, which means no TTI eviction takes place (infinite lifetime).

timeToLiveSeconds – The maximum number of seconds an element can exist in the cache regardless of use. The element expires at this limit and will no longer be returned from the cache. The default value is 0, which means no TTL eviction takes place (infinite lifetime).

Source

As per the definitions defined, the seconds which you have for Employee

 <cache name="com.sch.Employee"   
  maxElementsInMemory="100"   
  eternal="false"   
  timeToIdleSeconds="5"   
  timeToLiveSeconds="200" />

If you don't access the employee record with in 5 seconds of the deployment, it fetches from the database.

Any how, even the TTL is 200 sec, which is regardless of use.

So Make TTL - 0, TTI - 3600 and retest the application.

By this, TTL eviction will not take place and TTI is one hour so you have time to test your application

Upvotes: 1

Related Questions