26

I need a specific feature of hibernate that is StatelessSession and for that I need Hibernate's SessionFactory. The problem is I only have the entityManagerFactory. How can I get a StatelessSession in this scenario?

4 Answers 4

49

Option 1 through EntityManagerFactory

If you use Hibernate >= 4.3 and JPA 2.1 you can accces the SessionFactory from a EntityManagerFactory through <T> T EntityManagarFactory#unwrap(Class<T> cls).

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

Option 2 through EntityManager

If you use Hibernate >= 4.3 and JPA >= 2.0 then you can accces the Session from the EntityManager through <T> T EntityManagar#unwrap(Class<T> cls). From the Session you can obtain the SessionFactory.

Session session = entityManager.unwrap(Session.class);
SessionFactory sessionFactory = session.getSessionFactory();
2
  • vice versa is possible ? I have the SessionFactory object but for some reason I need EntityManagar
    – dom
    Jan 3, 2019 at 15:42
  • 1
    @dom no it’s not possible. Jan 3, 2019 at 18:35
10

Try to cast EntityManagerFactory to HibernateEntityManagerFactory.

Since EntityManagerFactory doesn't support unwrap() (unlike EntityManager), it seems to be the only way to achieve your goal.

2
  • 1
    Worked fine for me: HibernateEntityManagerFactory emFactory = (HibernateEntityManagerFactory) em.getEntityManagerFactory();
    – Tvaroh
    Jan 28, 2014 at 9:32
  • Since JPA 2.1 EntityManageFactory now provides an unwrap() method. Jun 26, 2020 at 8:51
7

Hibernate >= 4.3 supports JPA 2.1. So you can use EntityManagerFactory.unwrap like emf.unwrap(SessionFactory.class) there.

1
  • 1
    Another solution is to unwrap the EntityManager into a Session and then get the SessionManager from the session. This also works in jpa 2.0 Oct 22, 2014 at 21:14
0

I solved it by injecting it, defining the bean like this http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-session-factory-setup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.