4

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?

Erieze Lagera
  • 422
  • 6
  • 19

1 Answers1

11

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.

kostja
  • 60,521
  • 48
  • 179
  • 224
  • So by invoking createEntityManager, EntityManager needs to be closed explicitly. One more question, what did you mean by working with `transaction-scoped EntityManager`? – Erieze Lagera Sep 10 '14 at 15:09
  • Transaction-scoped EntityManagers are the default when you work with Java EE containers like JBoss or GlassFish. The nice thing about them that you do not have to care about their lifecycle - just request an instance and use it. [This post](http://piotrnowicki.com/2012/11/types-of-entitymanagers-application-managed-entitymanager/) nicely explains the differences – kostja Sep 10 '14 at 15:16
  • Hi Kostja. What's the consequence if we don't close entityManager? In a java ee Application is there a way to detect not closed entity manager ? – soung Sep 30 '17 at 12:17
  • An unclosed EM is a resource leak. In an EE application with transaction-scoped EMs, the implementation guarantees to close the EMs, so detecting unclosed ones is not required. – kostja Oct 14 '17 at 04:44