SessionFactory from EntityManager throws exception

戏子无情 提交于 2021-01-27 03:52:27

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/41619642/sessionfactory-from-entitymanager-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!