如何获得jpa监听器中的实体管理器或事务 [英] How to get entity manager or transaction in jpa listener

查看:615
本文介绍了如何获得jpa监听器中的实体管理器或事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在插入,删除和更新期间,我正在使用Hibernate事件侦听器(如 PostDeleteEventListener,PostInsertEventListener,PostUpdateEventListener )执行一些操作。现在我想使用JPA侦听器来做到这一点,因为如果我想从Hibernate移动到任何其他JPA提供程序,我的侦听器应该工作。 Hibernate侦听器给我事件,我可以从中获取事务并检查它是否已提交或回滚。 JPA侦听器仅向我提供实体对象。现在我怎样才能获得JPA侦听器中的事务或会话或实体管理器?提前致谢!!我使用Jboss作为我的CMT。

解决方案

从JPA 2.0开始,这不受支持。

在JPA 2.1中(预定在Java EE 7中),持久化提供程序将在托管环境(如JBoss应用程序服务器)中将实体侦听器视为CDI bean。从 JPA 2.1规范的提议最终草案,第96页:


当包含归档文件时,Java EE环境中的实体监听器类通过上下文和依赖注入API(CDI)[10]
支持依赖性
注入一个bean档案。使用CDI注入的实体监听器
类也可以定义用PostConstruct和PreDestroy
批注注释的生命周期
回调方法。这些方法将在注入
之后,实体监听器实例分别销毁
之前被调用。

因此,在JPA 2.1中,如果您创建了一个提供EntityManager的CDI生成器(只需使用@Produces注释@PersistenceContext字段),您就可以@将EntityManager注入到侦听器中。



同时,我并没有意识到任何干净或令人愉快的解决方法。我能想到的最不好的事情是将EntityManager配置为绑定在JNDI中,然后通过来自监听器中的JNDI查找来获得它。


I was using Hibernate event listener like PostDeleteEventListener, PostInsertEventListener, PostUpdateEventListener to do some operations during insert, delete and update. Now I would like to use JPA listener to do this because if I like to move from Hibernate to any other JPA provider my listener should work. Hibernate listener gives me event from which I can get the transaction and check whether its committed or rollback. JPA listeners only provides me the entity object. Now how can I get the transaction or session or entity manger in the JPA listener?? Thanks in advance!! I am using Jboss as my CMT.

解决方案

This is not supported as of JPA 2.0.

In JPA 2.1 (slated to be in Java EE 7), the persistence provider will treat entity listeners as CDI beans when in a managed environment (such as the JBoss app server). From the Proposed Final Draft of the JPA 2.1 spec, page 96:

Entity listener classes in Java EE environments support dependency injection through the Contexts and Dependency Injection API (CDI) [ 10 ] when the containing archive is a bean archive. An entity listener class that makes use of CDI injection may also define lifecycle callback methods annotated with the PostConstruct and PreDestroy annotations. These methods will be invoked after injection has taken place and before the entity listener instance is destroyed respectively

So in JPA 2.1, if you create a CDI producer that provides EntityManager (simply by annotating a @PersistenceContext field with @Produces), you can just @Inject the EntityManager into the listener.

In the mean time, I'm not aware of any clean or pleasant workaround. The "least worst" thing I can think of would be to configure the EntityManager to be bound in JNDI, then obtain it through a JNDI lookup from within the listener.

这篇关于如何获得jpa监听器中的实体管理器或事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆