I am working with a legacy database and had problems searching for an object. When user enters code say "250" to search for an object database might store this id in several ways: "0000250" or "250 ". It depends what other legacy application was used to enter the data. So I needed a way to find out if object already loaded in second level cache without hitting the database. I want to check if object with id "0000250" is in cache, if not then check id "250 " and only after that call load method. I created this function:
Code:
protected boolean isObjectInCache(Class clazz, String id){
SessionFactoryImplementor sessionFactoryImplementor =(SessionFactoryImplementor)getSessionFactory();
if(logger.isDebugEnabled()){
logger.debug("Checking if object is in cache: Class="+ clazz+", id="+id);
}
Cache cache = sessionFactoryImplementor.getSecondLevelCacheRegio n(clazz.getName());
if(cache==null){
return false;
}
CacheKey cacheKey = new CacheKey(id, Hibernate.STRING, clazz.getName(),
EntityMode.POJO, sessionFactoryImplementor);
CacheEntry cacheEntry = (CacheEntry)cache.get(cacheKey);
if(cacheEntry==null){
return false;
}
return true;
}
Is there an easier way to verify that without going into internals of hibernate and second level cache? Someone suggested to implement my own cache provider but then I would also need to implement my own dataaccess. I am looking for few line of code, not a whole project to do it.