Uzyskiwanie dostępu do sesji hibernacji z EJB przy użyciu EntityManager

Czy jest możliwe uzyskanie obiektu sesji Hibernate z Entitymanagera? Chcę uzyskać dostęp do API specyficznych dla hibernacji...

Już próbowałem czegoś takiego:

org.hibernate.Session hSession =
   ( (EntityManagerImpl) em.getDelegate() ).getSession();

Ale jak tylko wywołuję metodę w EJB, dostaję "wyjątek systemowy wystąpił podczas wywołania na EJB" z NullPointerException

Używam glassfish 3.0.1

Author: Bozho, 2010-12-02

4 answers

Bozho i partenon są poprawne, ale:

W JPA 2 preferowanym mechanizmem jest entityManager.unwrap (class)

HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
Session session = hem.getSession();

Myślę, że Twój wyjątek jest spowodowany tym, że próbujesz wrzucić do klasy implementacji (być może miałeś do czynienia z proxy JDK). Cast do interfejsu i wszystko powinno być w porządku(w wersji JPA 2 nie jest potrzebny casting).

 26
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:09:13

Z Hibernate EntityManager Docs, preferowanym sposobem jest:

Session session = entityManager.unwrap(Session.class);
 11
Author: Mouscellaneous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-29 19:05:39

Tak proste jak:

Session session = (Session) em.getDelegate();
 6
Author: jpkrohling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-02 13:39:27

Jeśli Twoje EntityManager zostało prawidłowo wstrzyknięte (używając @PersistenceContext) i nie jest równe null, to powinno działać:

org.hibernate.Session hSession = (Session) em.getDelegate();
 6
Author: Bozho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-02 13:40:17