Get Hibernate SessionFactory from JPA's entityManagerFactory

前端 未结 4 1132
攒了一身酷
攒了一身酷 2021-02-01 05:35

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 g

相关标签:
4条回答
  • 2021-02-01 05:40

    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.

    0 讨论(0)
  • 2021-02-01 05:53

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

    0 讨论(0)
  • 2021-02-01 05:56

    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();
    
    0 讨论(0)
  • 2021-02-01 06:02

    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

    0 讨论(0)
提交回复
热议问题