Junior — Middle
Can you explain the differences between EntityManager and SessionFactory in the context of ORM?
sobes.tech AI
Answer from AI
In the context of ORM (for example, Hibernate in Java), SessionFactory and EntityManager serve different roles:
-
SessionFactory is a factory that creates
Sessionobjects. It is thread-safe and usually created once during the application's lifetime. It is responsible for configuration and creating sessions for database interaction. -
Session is an object through which interaction with the database occurs: loading, saving, updating entities.
-
EntityManager is an interface from the JPA specification that provides an API for managing the lifecycle of entities and executing queries. It can internally use
Session(in Hibernate).
Thus:
SessionFactoryis a factory for creating sessions.EntityManageris an interface for working with entities, similar toSessionin JPA.
Example usage:
// Obtaining EntityManager from EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-pu");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// operations with entities
em.getTransaction().commit();
em.close();