I can’t write the perfect solution in any way - I want to create a cache in order to upload frequently called data to it. For example, we have the code:

public static List<EntityCity> getCities() { Session session = HibernateUtils.getSessionFactory().openSession(); session.beginTransaction(); List<EntityCity> list = (List<EntityCity>) session.createQuery("...").list(); session.getTransaction().commit(); session.close(); return list; } 

I call this:

  Object fromCache = MyCache.get(MyCacheKeys.ENTITY_CITIES); if (fromCache != null) { return (List<EntityCity>) fromCache; } 

The MyCacheKeys class looks like this:

 public class SMCacheKeys { public static String ENTITY_CITIES = "from EntityCity where active = 'true'"; } 

The cache is:

 public class MyCache { private static HashMap<Integer, Object> cache = new HashMap<Integer, Object>(); ... 

Tell me the solution is better)

  • If you correct grammatical errors, correct without errors !! - Jenkamen

2 answers 2

Hiberneyt has a ready solution in the form of second level cashe. I advise you to look in his direction

  • no thanks. I don't want to use it - Jenkamen
  • Why not? Why not try a standard solution instead of reinventing the wheel? I don't know how in hibernate, but the cache in Oracle TopLink works pretty well. - cy6erGn0m
  • The cache should be transparent, i.e. written by yourself. - Jenkamen

Look towards SoftReference Caching