I'm about in 1 year developing systems in Java using JPA as database framework.
Every time I query, I do not close the EntityManager, IMO understanding is that JPA automatically closes EntityManager after executing the query like
getSingleResult() or getResultList()
If not then does garbage collection will collect it to dispose?
Application-managed EntityManagers (the ones you get from the EntityManagerFactory by invoking emf.createEntityManager()
) have to be closed explicitly.
EDIT: you do not have to close the EM after each query, but make sure that you do close it before returning from the method that created it. A common approach is to embed EM in a try/catch/finally
block, invoking em.close();
in the finally
case.
If you are working with a transaction-scoped EntityManager in a Java EE compliant container, the EntityManager is created by the container during a transaction and will be closed when the transaction completes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With