EntityManager中的SessionFactory抛出异常

时间:2017-01-12 17:40:42

标签: java hibernate jpa entitymanager

我试图通过以下几行从JPA的EntityManager中获取Hibernate的SessionFactory:

@PersistenceContext
EntityManager manager;

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

但它抛出了这个例外:

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)
...

这可能是什么原因?

提前致谢

1 个答案:

答案 0 :(得分:2)

您无法使用unwrap获取会话工厂,您可以使用它来获取会话 从会议开始,如果需要,您可以获得工厂:

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