Search code examples
javahibernatejpaentitymanager

SessionFactory from EntityManager throws exception


I'm trying to get the Hibernate's SessionFactory from JPA's EntityManager with the following lines:

@PersistenceContext
EntityManager manager;

public SessionFactory getSessionFactory(){
    sessionFactory = manager.unwrap(SessionFactory.class);
}

But it throws this exception:

org.springframework.orm.jpa.JpaSystemException: Hibernate cannot unwrap interface org.hibernate.SessionFactory; nested exception is javax.persistence.PersistenceException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418)
...

Caused by: javax.persistence.PersistenceException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.unwrap(AbstractEntityManagerImpl.java:1489)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...

What could be the reason for this?

Thanks in advance


Solution

  • You can't use unwrap to get session factory, you can use it go get the session.
    From the session, you can get the factory if you need:

    public SessionFactory getSessionFactory(){
        Session session = manager.unwrap(Session.class);
        sessionFactory = session.getSessionFactory(); 
    }