Java 使用 EntityManager 从 EJB 访问 Hibernate Session

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4335570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:04:57  来源:igfitidea点击:

Accessing Hibernate Session from EJB using EntityManager

javahibernatejpajakarta-eeglassfish-3

提问by Bogdan

Is it possible to obtain the Hibernate Session object from the EntityManager? I want to access some hibernate specific API...

是否可以从 EntityManager 获取 Hibernate Session 对象?我想访问一些休眠特定的 API...

I already tried something like:

我已经尝试过类似的东西:

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

but as soon as I invoke a method in the EJB I get "A system exception occurred during an invocation on EJB" with a NullPointerException

但是一旦我在 EJB 中调用一个方法,我就会收到带有 NullPointerException 的“在 EJB 上调用期间发生系统异常”

I use glassfish 3.0.1

我使用玻璃鱼 3.0.1

采纳答案by Sean Patrick Floyd

Bozhoand partenonare correct, but:

Bozhopartenon是正确的,但是:

In JPA 2, the preferred mechanism is entityManager.unwrap(class)

在 JPA 2 中,首选机制是entityManager.unwrap(class)

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

I think your exception is caused because you are trying to cast to an implementation class (perhaps you were dealing with a JDK proxy). Cast to an interface, and everything should be fine (in the JPA 2 version, no casting is needed).

我认为你的异常是因为你试图转换为一个实现类(也许你正在处理一个 JDK 代理)。转换到一个接口,一切都应该没问题(在 JPA 2 版本中,不需要转换)。

回答by jpkrohling

As simple as:

就这么简单:

Session session = (Session) em.getDelegate();

回答by Bozho

If your EntityManageris properly injected (using @PersistenceContext) and is not null, then the following should work:

如果您EntityManager正确注入(使用@PersistenceContext)并且不为空,则以下内容应该有效:

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

回答by Mouscellaneous

From Hibernate EntityManager docs, the preferred way of doing it is:

从 Hibernate EntityManager 文档中,首选的做法是:

Session session = entityManager.unwrap(Session.class);