Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity manager needs to be closed every query?

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?

like image 496
Erieze Lagera Avatar asked Jan 09 '23 20:01

Erieze Lagera


1 Answers

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.

like image 72
kostja Avatar answered Jan 13 '23 13:01

kostja