Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 511
Marcelo Abiarraj Avatar asked Jan 12 '17 17:01

Marcelo Abiarraj


People also ask

Can SessionFactory be reused in Hibernate?

hibernate. SessionFactory)**: SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.

How do I get session factory from EntityManager?

If a developer uses JPA, there's a neat little trick to get the Hibernate SessionFactory from JPA's EntityManager. First, perform a quick unwrap method call to get the Hibernate Session from the JPA EntityManager. Then call the Hibernate Session's getSessionFactory() method.

Does Hibernate use EntityManager?

Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager . EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation.


1 Answers

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(); 
}
like image 130
Nir Levy Avatar answered Oct 06 '22 01:10

Nir Levy