2.4. Obtaining an EntityManager in a Java SE environment

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
em.close();
...
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.