This question touches a little bit on the JPA specification and a little
bit on the EJB specification. I made a judgment call that this was the
proper list of which to ask the question. My apologies if I'm in the wrong
place.
In JPA 2.0, one may build up the raw materials of a criteria query and
cache them (they are designed to be serializable according to JPA section
6.9). OK, fine.
Suppose I have a stateless session bean that would like to assemble a bunch
of CriteriaQuery objects in advance and stash them somewhere for later use
in a business method by an injected EntityManager.
Where would be the best place to maintain this in-memory collection?
1. Assemble the objects in a @PostConstruct method and store the results as
some kind of immutable Map in an instance variable of the session bean.
This obviously would be better than creating these CriteriaQuery objects
for every query, but is still creating them too frequently.
2. Using synchronized access to a static immutable Map field, do the same
as (1), but check first to see if the work has already been done. This is
in violation of section 21.2.2 of the EJB 3.1 specification which says that
synchronization primitives are forbidden.
2a. Use some kind of concurrent map in a static immutable Map field to
accomplish (2). My reading of the specification however is that 21.2.2 is
still violated in this case.
3. Stored...in a @Singleton bean? maybe? that is then injected into the
actual bean that wants to use that bean's CriteriaQuery cache? This feels
like simultaneously the most awkward and the only permitted solution.
Since this must be a problem others have faced I would like to understand
what others would recommend here.
Have a good weekend.
Best,
Laird
--
http://about.me/lairdnelson