aspose file tools*
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
JavaRanch » Java Forums » Caching » EhCache
Bookmark "EhCache Sample Code" Watch "EhCache Sample Code" New topic
Author

EhCache Sample Code

kritika ram
Greenhorn

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.

CacheModel.java

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);
}
}

CacheFactory.java

public class CacheFactory implements CacheEntryFactory
{

public CacheFactory()
{

}

public Object createEntry(Object key) throws Exception
{
CacheEntryKey Key = (CacheEntryKey) key;
int new_ID = Key.getID();
System.out.println(new_ID);
CacheVO VO = new CacheVO();
String query = null;
Class.forName("com.mysql.jdbc.Driver");
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);

while(rs.next())
{
VO.setAge(rs.getInt("Age"));
VO.setName(rs.getString("Name"));
}

return VO;
}
}

CacheDAO.java

public class CacheDAO
{

public CacheVO fetchContent(int ID) throws Exception
{
CacheVO VO = null;
CacheEntryKey key = new CacheEntryKey();
key.setID(ID);
CacheManager samplemanager = CacheManager
.getInstance("D:/ehcache.xml");
Cache cache = samplemanager
.getCache("sampleCache1");
Serializable value = cache.get(key);
VO = (VistaCacheVO) value;
return VO;
}
}

CacheEntryKey.java

public class CacheEntryKey implements Serializable
{
private int ID;

public int getID()
{
return ID;
}

public void setID(int id)
{
ID = id;
}
}

CacheVO.java

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: http://aspose.com/file-tools
 
subject: EhCache Sample Code