Search code examples
javajakarta-eejpaeclipselink

When to create a new EntityManager


I'm working with JPA (Eclipselink) in an unmanaged (no EJBs) context.

My question is: How long should I keep a Entity Manager open?

Swing Application: - One open Entity Manager as long as the application is running - Each single action a new Entity Manager

Web Application: - One Entity Manager per (distinct) action - One per request - One per session - One per application(-scope), asuming the application is thread safe

Best Regards


Solution

  • For the Swing application, I will opt for the one EntityManager per action since it's quite cheap to create one and you might not want to keep so many entites managed by EntityManager when you're not using it (this is One EntityManager per application).

    For the Web application, typical pattern used is "OpenSessionInView" pattern (Session applied to Hibernate but it can be applied to EntityManager as well since both are logically providing the same role/functionality).

    More info here: https://community.jboss.org/wiki/OpenSessionInView

    Hope this helps.