As for our requirement, instead of injecting EntityManger into other EJBs, we are having utility class which will return the reference to entitymanager.
There are probably very good reasons but what are the constraints exactly, why can't you use injection? Anyway, is the lookup identified as being a problem? Did you measure something? How much time does the lookup represent compared to the total processing time? Is it non negligible?
In order to avoid JNDI lookup, we want to cache the reference to entity manager in hashmap etc...
To be honest, that fact that you are asking questions here is a strong hint that you shouldn't go this way. What about transaction management? What about exceptions handling (you're supposed to discard the EM after an exception)? What about memory management?
If we cache the entityManager, then will it hold the connection as long as the reference is active?
Resources (as long as they have been acquired) won't be released, so yes. From the Hibernate EM documentation:
A EntityManagerFactory
is an
expensive-to-create, threadsafe object
intended to be shared by all
application threads. It is created
once, usually on application startup.
An EntityManager
is an inexpensive,
non-threadsafe object that should be
used once, for a single business
process, a single unit of work, and
then discarded. An EntityManager
will not obtain a JDBC Connection (or
a Datasource) unless it is needed,
so you may safely open and close an
EntityManager
even if you are not
sure that data access will be needed
to serve a particular request*. (This
becomes important as soon as you are
implementing some of the following
patterns using request interception.)
...
And later:
...
A call to close()
marks the end of an EntityManager
. The main implication of close()
is the release of resources - make sure you always close and never outside of guaranteed finally block.
There is no magic. If the EM needs to interact with the database, it will acquire a connection. And this connection won't be released if you don't close
the EntityManager. Check the source code of the underlying Hibernate Session
if you want.
Will there be any change in the transaction management?
Well, you didn't say anything about what you're currently using (a container-managed entity manager? an application-managed entity manager?) and you didn't explain how transactions are managed (JTA entity manager? resource-local entity manager?). Anyway, the answer is... probably.
Maybe you should explain how things are currently working (before starting to cache entity managers).
And I would personally measure things, I'm not convinced there is a problem. Unless you prove there is a problem, what you're trying to do is not worth the troubles.