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

筅森魡賤 提交于 2019-11-30 14:16:00

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!