Suppose you are using JPA in standalone mode. You have a DAO which has creates EntityManger(s). Is it best practise to just create one EntityManager and reuse that across invocations or is it better to close() the EntityManager at the end of every DAO API and then create a new one at the beginning?
posted 5 years ago
Ideally you would create a new EntityManager per server request.
You definitely need to use the same one for the duration of a transaction.
For reads, you could use a new one per query, but would be best to reuse the same one for the duration of a request, so you need some context somewhere to pass the em to the DOA, or use a thread local that is set at whatever part of your app that has a concept of a transaction or request, or give your DOA this concept, or use a third party transaction manager such as EJB or Spring.
The issues are:
- for a transaction, you must use the same EntityManager
- an EntityManager contains a persistence context, that will track everything read through it, so to avoid bloated memory, you should acquire a new one, or clear it at some point
- if you read the same object through two different EntityManager you will get different objects back, so will loose object identity, which is something to consider