Video in progress
How are EntityManager and the Hibernate Session related?
EntityManager is the JPA interface and Session is Hibernate's. In Hibernate 6, Session extends EntityManager directly, so they are the same object. When you need Hibernate's API, you switch to it with em.unwrap(Session.class).
📖 Answer
In the same way, EntityManagerFactory and SessionFactory are one thing. One factory is created per application (a heavy object holding metadata and caches), while a new EntityManager is opened for each transaction or request.
In Spring you usually get a proxy:
@PersistenceContext
private EntityManager em; // actually a shared proxy that hands out the current transaction's em
That's why you can safely use a single em field in a singleton service: it is thread-safe, because every call is routed to the real EntityManager bound to the current transaction. The real EntityManager itself is not thread-safe.
If you need something Hibernate-specific:
Session session = em.unwrap(Session.class);
session.setJdbcBatchSize(50);
In practice I start with the JPA API and call unwrap only when there is a clear need.
Sign up to mark studied questions and save your progress.