1

I have some common data that all of my EJBs will need, so I decided to write 1 EJB to go and get the data, while the other EJBs will call the first EJB to get the data. Now I want to cache the data in the EJB so that it does not have to go back to the database each time it is asked for the data.

So, how do I cache the data in the EJB and maybe pull a fresh copy every 1 hour or so. Can I do this with Ehcache? Or am I thinking about this all wrong, and there is a better way to do it.

Thanks

jeha
  • 10,562
  • 5
  • 50
  • 69
Tony Borf
  • 4,579
  • 8
  • 43
  • 51

2 Answers2

2

I think you must use the frameworks that already do this work. By example:

  1. If you are using JPA for access to database you can configure the cache in the persistence.xml and its will depend of your Persistence Provider (Hibernate, Toplink, etc).
  2. If you are using Hibernate it has support for third party Cache Frameworks like EHCache.
  3. Anyway you can configure EHCache (or other similar) for do this work.
Ernesto Campohermoso
  • 7,213
  • 1
  • 40
  • 51
1

Yes you can use ehcache for that purpose but this is then still not 'cached' inside the EJB and remains inside the memory of the node the server is running on.

In a stateless EJB you only have this option whereas in a stateful EJB you could keep the data in the EJB (but having a stateful EJB for such a long time is just stupid), so this is not a really alternative.

One other approach is to use some data holder inside the EJB in a static manner. E.g. create a static map that keeps the data or a static list. Of course this is only per class loader, but as long as the class isn't removed from the classloader the static data stays there. This is then really inside the memory. For refreshing you could create a quartz job that periodically updates the data inside the static member.

rit
  • 2,308
  • 3
  • 19
  • 27
  • I started with having an enum list in my EJB, but since I have this data in a database I didnt want to manage it in two places. – Tony Borf Oct 19 '11 at 19:50
  • Ok. But you could load the enums into the ejb once (if they don't change)? – rit Oct 19 '11 at 19:54