Marcelo Abiarraj
Marcelo Abiarraj

Reputation: 309

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

Upvotes: 8

Views: 7782

Answers (1)

Nir Levy
Nir Levy

Reputation: 12953

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(); 
}

Upvotes: 8

Related Questions