7

I have few tables with very few entries in them and they will never change dynamically . so i want to cache the whole table in memory to reduce load on DB. I can easily achieve that by a static Map and populating the map in a static block.

i was wondering whether the same is possible in a more effective way by Ehcache + hibernate?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
dpsdce
  • 5,290
  • 9
  • 45
  • 58
  • Can you provide simple map implementations for cache? – Rachel Jan 31 '12 at 15:56
  • 1
    just declare a public static map, add the values you want to cache in the map, and start a thread which will refresh this map every 12 hrs or smthing. – dpsdce Feb 02 '12 at 04:31
  • Thanks Novice, I have implemented static map but am not refreshing it every 12 hrs. I will look into it if there is need. – Rachel Feb 02 '12 at 16:37

2 Answers2

7

Ehcache has a lot more features than a Map:

  • limit the maximum number of elements in memory
  • overflow to disk (if the above number is exceeded)
  • set a time-to-live and time-to-idle for elements
  • allows replication within a cluster

If you don't need any of those, you can safely use a Map - it will be easier to configure.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
6

The advantage of a real second-level cache over a static map is that you get the advantage of in-memory access by still keeping the same way of defining, accessing and traversing your entities: by using the Hibernate session (or entity manager).

You may keep relationships with other entities (even not cached); you may use a query cache and still perform queries over these entities (and results of these queries will be cached as well).

In short, it's transparent, offers more options as Bozho said, and is much easier to use because cached entties are used the same way as other entities.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • i agree that using Ehcahe will keep the the code uniform (the way we access other entities) but is there a way to prepopulate the ecache at server start as i can do in map implementation by a static block to populate the map initially? – dpsdce May 25 '11 at 08:56
  • Executing a HQL query loading all the entities should do the trick : select c from CachedEntity c. – JB Nizet May 25 '11 at 09:35