EntityManager stores its data using threadlocal, so it might be nice to keep a static link to it, since all threads accessing it will be processed independently. In fact, I wonβt be surprised if the EJB context is stored in the EntityManager in a static way using the singleton pattern.
Personally, I would never define it in a static way. This seems unnecessary, and in the worst case, there may be some unforeseen side effects.
One of the problems I see is the ability to inadvertently access entityManager from a static method:
public class BaseDaoThatEveryDaoExtends { @PersistenceContext private static EntityManager entityManager; public static void doSomeStaticWork(){ ... entityManager.doSomething;
I could see that EntityManager is not being entered and in this case NPE appears.
In addition, some issues related to testing / bullying using the EntityManager may occur.
source share