Nov 7, 2018

When to close a JPA EntityManger in web applications

If you are managing the EntityManager lifecycle yourself (as opposed to having Container Managed Persistence done by a J2EE) then you need to close the EntityManager yourself or at least detach entities.

EntityManager are lightweight object so there is no need for just having one, you can create one for each transaction and close it after the transaction is committed.

All the entities that load/persist through an EntityManager stay in memory until you explicitly detach the entities from it (via EntityManager.detach() or EntityManager.clear() or EntityManager.close()). 

It's better to have short-lived EntityManagers. If you persist a lot of entities via the same EntityManager without detaching them after you will run out of memory,  even  you persist each entity in it's own transaction.