Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes EhCache and the fly likes EhCache Sample Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Caching » EhCache
Bookmark "EhCache Sample Code" Watch "EhCache Sample Code" New topic

EhCache Sample Code

kritika ram

Joined: Aug 25, 2006
Posts: 12
I have to write sample code for Ehcache which loads values into the cache from the database automatically if it is not present in cache.

I have a model which calls the DAO. The DAO has the implementation of creating the cache based on the ehcache.xml configuration. I fail to see the connection between the DAO and the CacheEntryFactory which has a method createEntry() which is supposed to load the cache with the values. Is EhCache supposed to call creatEntry() internally ? If so, it is not calling and nothing gets printed on the console.

Iam attaching the codes here. Sorry if it is too long. Thanks for all the help.

public class CacheModel
public static void testCache() throws Exception

VistaCacheDAO sampledao = new VistaCacheDAO();
VistaCacheVO VO = sampledao.fetchContent(1);
String name = VO.getName();
int age = VO.getAge();
System.out.println ("Name :");
System.out.println (name);
System.out.println ("Age :");
System.out.println (age);

public class CacheFactory implements CacheEntryFactory

public CacheFactory()


public Object createEntry(Object key) throws Exception
CacheEntryKey Key = (CacheEntryKey) key;
int new_ID = Key.getID();
CacheVO VO = new CacheVO();
String query = null;
Connection con = DriverManager.getConnection(
"jdbc:mysql://xxxxxxxx:xxxx/xxxxxx", "root", "root");
Statement st = con.createStatement();
ResultSet rs = null;
query = "select Name, Age from testcache where ID="+ new_ID;
rs = st.executeQuery(query);


return VO;

public class CacheDAO

public CacheVO fetchContent(int ID) throws Exception
CacheVO VO = null;
CacheEntryKey key = new CacheEntryKey();
CacheManager samplemanager = CacheManager
Cache cache = samplemanager
Serializable value = cache.get(key);
VO = (VistaCacheVO) value;
return VO;

public class CacheEntryKey implements Serializable
private int ID;

public int getID()
return ID;

public void setID(int id)
ID = id;

public class CacheVO implements Serializable
private int Age;

private String Name;

public String getName()
return Name;

public void setName(String name)
Name = name;

public int getAge()
return Age;

public void setAge(int age)
Age = age;

I agree. Here's the link:
subject: EhCache Sample Code
Similar Threads
returning an int
Identity issue for EJB3.0 Entity along with Hibernate HBM configuration
"Cached Item Was Locked" causing Select Statement using Hibernate and EHCache
hibernate composite key problem
composite-id hibernate problem