2.4. Obtaining an EntityManager in a Java SE environment

download PDF
An entity manager factory should be considered as an immutable configuration holder, it is defined to point to a single datasource and to map a defined set of entities. This is the entry point to create and manage EntityManagers. The Persistence class is bootstrap class to create an entity manager factory.
// Use persistence.xml configuration
EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");
EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager
// Work with the EM
emf.close(); //close at application end
An entity manager factory is typically created at application initialization time and closed at application end. It's creation is an expensive process. For those who are familiar with Hibernate, an entity manager factory is very much like a session factory. Actually, an entity manager factory is a wrapper on top of a session factory. Calls to the entityManagerFactory are thread safe.
Thanks to the EntityManagerFactory, you can retrieve an extended entity manager. The extended entity manager keep the same persistence context for the lifetime of the entity manager: in other words, the entities are still managed between two transactions (unless you call entityManager.clear() in between). You can see an entity manager as a small wrapper on top of an Hibernate session.
Red Hat logoGithubRedditYoutubeTwitter


Try, buy, & sell


About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.