@Autowired vs @PersistenceContext for EntityManager bean

You shouldn’t use @Autowired.
@PersistenceContext takes care to create a unique EntityManager for every thread. In a production application you can have multiple clients calling your application in the same time. For each call, the application creates a thread. Each thread should use its own EntityManager. Imagine what would happen if they share the same EntityManager: different users would access the same entities.

usually the EntityManager or Session are bound to the thread (implemented as a ThreadLocal variable).

Source: https://stackoverflow.com/a/42074452/2623162

EntityManager instances are not thread-safe. 

Source: https://docs.oracle.com/cd/E19798-01/821-1841/bnbqy/index.html

Please notice that @PersistenceContext annotation comes from javax.persistence package, not from spring framework. In JavaEE it is used by the JavaEE container (aka the application server) to inject the EntityManager. Spring borrowed the PersistenceContext annotation to do the same: to inject an application-managed (= not container-managed) EntityManager bean per thread, exactly as the JavaEE container does.

Leave a Comment