1

Considering a simple servlet app, I simply use a global(shared) emf:EntityManagerFactory instance which is initialized by init():void method by servlet instance load.
For each request I get a em:EntityManager from emf, use it, then close it(em).

I just realized EntityManagerFactory has got a close() method, so the question is, should I get a EntityManagerFactory for each request just as same as I do for EntityManager?
What is the best practice to use the EntityManager? is it okay to get -> do -> close for each request?

kryger
  • 11,746
  • 8
  • 41
  • 60
  • Look here i think there is your answer :) http://stackoverflow.com/questions/4225638/how-frequently-should-i-create-an-entitymanager – pL4Gu33 May 01 '14 at 14:42
  • Look here is your answer http://stackoverflow.com/questions/7862700/best-practice-to-get-entitymanagerfactory – Asif Bhutto May 01 '14 at 14:52
  • If you intend to use the same `EntityManagerFactory` on different servlets of the same context, have a look at http://stackoverflow.com/questions/22628862/how-to-share-entitymanagerfactory-in-jpa/22629592#22629592, which also answers your question. – VH-NZZ May 01 '14 at 15:27
  • @okiharaherbst Thanks dude –  May 01 '14 at 15:28
  • @user35736644892 Thanks buddy :D –  May 01 '14 at 15:29
  • @parsaporahmad Seriously consider using listeners as they seriously reduce coupling and help separate concerns. – VH-NZZ May 01 '14 at 15:31
  • @parsa porahmad think about more than one servlet, other wise you have to open and close it in each servelt, that will be so bad , open and close EMF in every servelt. – Asif Bhutto May 01 '14 at 15:39

1 Answers1

0

You should continue to use a single EntityManagerFactory. Call it's close method in your servlet's destroy method.

Steve C
  • 17,352
  • 4
  • 29
  • 34