Q:

Can I inject properties into a JPA Entity Listener

I could prototype this and see what happens, but I am being lazy. I want to be able to inject an EJB3 into my JPA Entity Listener so that it can access functionality of the EJB during the PrePersist operation. Is that possible? If not... then under JBoss, will the Listener be created once, or once per method invocation? I guess I am trying to understand how lightweight each invocation will be in terms of doing JNDI lookups etc
Anyone know of a good source of info on these topics as my brief googling didn't turn anything up.

A:

You'll have to resort to JNDI lookups to access other EJBs from your EntityListener. I've never seen a way to inject them directly -- I assume this is because of the semantics of the EntityListener.
What follows is from my experience with JBoss 4.0.x and 4.2.x.
As an example, consider @PostPersist -- called after the insert statement is executed. There's two issues to consider:

The database won't reflect the current entity if you open another session to query it (even with a JNDI lookup). There's no guarantee that the transaction will be committed just because the session was flushed. You won't have autogenerated primary keys either.
Entity listeners don't seem to be intended for anything aside from updating managed fields or verifying data integrity before a commit (not unlike a database trigger), which severely limits their utility. Specifically, in JBoss, you can't even lookup the current security context to log who is making the change. That sucks.

With respect to how many entity listeners exist, my experience in JBoss 4.2.x was that only one instance ever existed, and the methods were called in the context of a container thread. However, this may not be true in a clustered setup. Either way, I would recommend you NOT cache your references in any entity listeners -- it's not clear what exactly JBoss might do to them (passivate them? I hope not, but you never know!).

