I am new to Hibernate and I\'m not sure whether to use a Hibernate SessionFactory
or a JPA EntityManagerFactory
to create a Hibernate Session
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.