I am new to Hibernate and am unclear of whether to use a SessionFactory
or EntityManagerFactory
to obtain the hibernate session. What is the difference between the two? Pros & Cons?
Prefer EntityManagerFactory
and EntityManager
. They are defined by the JPA standard.
SessionFactory
and Session
are hibernate-specific. The EntityManager
invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager
, you can obtain the session by calling:
Session session = entityManager.unwrap(Session.class);
I want to add on this that you can also get Hibernate's session by calling getDelegate()
method from EntityManager
.
ex:
Session session = (Session) entityManager.getDelegate();
I prefer the JPA2 EntityManager
API over SessionFactory
, because it feels more modern. One simple example:
JPA:
@PersistenceContext
EntityManager entityManager;
public List<MyEntity> findSomeApples() {
return entityManager
.createQuery("from MyEntity where apples=7", MyEntity.class)
.getResultList();
}
SessionFactory:
@Autowired
SessionFactory sessionFactory;
public List<MyEntity> findSomeApples() {
Session session = sessionFactory.getCurrentSession();
List<?> result = session.createQuery("from MyEntity where apples=7")
.list();
@SuppressWarnings("unchecked")
List<MyEntity> resultCasted = (List<MyEntity>) result;
return resultCasted;
}
I think it's clear that the first one looks cleaner and is also easier to test because EntityManager can be easily mocked.
By using EntityManager, code is no longer tightly coupled with hibernate. But for this, in usage we should use :
javax.persistence.EntityManager
instead of
org.hibernate.ejb.HibernateEntityManager
Similarly, for EntityManagerFactory, use javax interface. That way, the code is loosely coupled. If there is a better JPA 2 implementation than hibernate, switching would be easy. In extreme case, we could type cast to HibernateEntityManager.
EntityManager interface is similar to sessionFactory in hibernate. EntityManager under javax.persistance package but session and sessionFactory under org.hibernate.Session/sessionFactory package.
Entity manager is JPA specific and session/sessionFactory are hibernate specific.
EntityManagerFactory is the standard implementation, it is the same across all the implementations. If you migrate your ORM for any other provider like EclipseLink, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied to hibernate APIs and cannot migrate to new vendor.
来源:https://stackoverflow.com/questions/5640778/hibernate-sessionfactory-vs-entitymanagerfactory