Can you access EntityManagers from EntityListeners?

I know that the JSR-000220 Enterprise JavaBeans 3.0 Final Release specification (persistence) states:

"In general, portable applications should not invoke EntityManager or Query operations, access other instances of an object, or change relationships in a lifecycle callback method."

It looks extremely restrictive. We have a situation in which we would like to access the EntityManager from within the EntityListener.

Does anyone encounter any adverse effects / pitfulls when using EntityManager from Listener on Jboss / Glassfish or any other application server, for that matter?

+4
source share
1 answer

You are actually right. JPA talks about this, and in this case, it offers listeners EJB (or Spring AOP in an environment other than Java EE).

I do not know the purple of your listener. But just pose cross-cutting issues such as logging, authentication, and routing within it. For example, the Hibernate help documentation uses listeners to audit the log of all object modifications. This can be done by EJB listeners (or Spring AOP in a non-Java EE environment) when EJB listeners can use entity manager. The Java EE specification allows this. Therefore, EJB listeners use the same ENC used by the target EJB, and thus also use the same persistence context (entity manager).

If you want, see my profile. I have many problems related to ORM.

Yours faithfully,

+2
source

All Articles