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?
Asked
Active
Viewed 218 times
1

kryger
- 12,906
- 8
- 44
- 65
-
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
-
@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 Answers
0
You should continue to use a single EntityManagerFactory
. Call it's close method in your servlet's destroy
method.

Steve C
- 18,876
- 5
- 34
- 37
-
EntityManagerFactory are very expensive and heavyweight objects, they should be open on application start up time – Asif Bhutto May 01 '14 at 14:53
-
1
-
Thanks dude, I appreciate your help. It's cool when `user3...92`' comment is as same as your answer, haha haha. – May 01 '14 at 15:00