使用 EntityManager 从 EJB 访问 Hibernate 会话

发布于 2024-10-05 14:33:27 字数 318 浏览 1 评论 0 原文

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

我已经尝试过类似的操作:

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

但是一旦我调用 EJB 中的方法,我就会得到“在 EJB 上调用期间发生系统异常”并出现 NullPointerException

我使用 glassfish 3.0.1

Is it possible to obtain the Hibernate Session object from the EntityManager? I want to access some hibernate specific 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

I use glassfish 3.0.1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小梨窩很甜 2024-10-12 14:33:27

Bozhopartenon 是正确的,但是:

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

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

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

Bozho and partenon are correct, but:

In JPA 2, the preferred mechanism is 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).

分開簡單 2024-10-12 14:33:27

从 Hibernate EntityManager 文档来看,首选的方法是:

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

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

Session session = entityManager.unwrap(Session.class);
笑看君怀她人 2024-10-12 14:33:27

很简单:

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

As simple as:

Session session = (Session) em.getDelegate();
疯到世界奔溃 2024-10-12 14:33:27

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

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

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

org.hibernate.Session hSession = (Session) em.getDelegate();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文