I have just started migrating my homegrown persistence framework to JPA.
Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.
I intend in all places to close them, but do I HAVE to?
At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.
If you don't close it your entities will be kept as attached, even after you're done using them. Your context will be kept alive even when you can no longer access your EM. The JPA Specification contains more details.
I have used @PersistenceContext to inject Transactional EntityManager to my DAOs and this implies that spring will take care of creating and closing EntityManager for me. However in my previous implementation I used to create and close EntityManager from DAOs, which is now replaced using spring.
clear. Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
The last state, Detached, represents entity objects that have been disconnected from the EntityManager. For instance, all the managed objects of an EntityManager become detached when the EntityManager is closed.
It depends how you obtained it.
If you created it using EntityManagerFactory you will have to close it no matter what framework you use.
If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand (AFAIK it will cause RuntimeException).
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