How frequently should I create an EntityManager?

后端 未结 3 917
陌清茗
陌清茗 2020-12-30 21:21

I have an EntityManagerFactory for which I can create one (or multiple) EntityManager instances. I\'m using a Servlet environment, and I\'ve got on

相关标签:
3条回答
  • 2020-12-30 21:27

    One EM for the whole servlet doesn't sound good. If you're not using container-managed EM's (for example EJB3) then the recommentation is to use an EM for a particular unit of work.

    In a web application context your third suggestion (one per HTTP request) sounds good. However this may lead you down a pitfall where you are tying your service layer with your db layer (your service layer shouldn't even be aware of the existance of an EM).

    Another approach would be to programatically demark transactions in your DAO and get your DAO to use a new EM for for every method call.

    Edit: EMs are cheap to create as opposed to EMFs which have a significant overhead. Using one EMF (which it appears that you do) and lots of EMs is the way to go.

    0 讨论(0)
  • 2020-12-30 21:31

    Yes, I agree with NimChimpsky and Qwerky to use EJB3.x when accessing DBs and to use one EM per unit of work.

    0 讨论(0)
  • 2020-12-30 21:38

    we do one injected entity manager for each slsb, - and the slsb is itself accessed via a delegate, of which there is one per session, which looks up the local/remote interface. Using ejb3.0.

    0 讨论(0)
提交回复
热议问题