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
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With