Hibernate EntityManager, is it supposed to be used as a singleton? Hibernate EntityManager, is it supposed to be used as a singleton? spring spring

Hibernate EntityManager, is it supposed to be used as a singleton?


See this Article: JPA Architecture it explain it very well.

In General you need a single Entity Manager per transaction. And this Entity Manager must not be used in two transactions at the same time.

Clairification: I mean, do not use a single Entity Manager for different unit of works. Typical one transaction in one unit of work, if you have different transactions of one unit of work, then you can use the same Entity Manager

If you use Spring then Spring do this handling for you if you use the @PersistenceContext annotation to inject the EntityManager. Per default Spring "bind" the the injected EntityManager (via a proxy) to the current transaction. (And the transaction is "bound" to the thread.)

@See Spring Reference 13.5.2 Implementing DAOs based on plain JPA - it contains a interesting paragagraph after the code examples.


You need a dependency injection framework like Spring or Google Guice to inject objects into your class otherwise it may not be injected automatically for you.

Basically this is an annotation provided by JPA which will work with in tandem with hibernate or any other ORM framework per say but you need a DI framework to inject the objects.

Regarding the single instance of entity manager i don't think you need that if you go by Spring since it takes care of managing the instances and the transactions for you by tying your entity manager with the jpa transaction.