views:

512

answers:

3

How can I inject an EJB into a domain object (an JPA entity) with Java EE 6?

+3  A: 

EJB3 client injection applies to "managed classes" such as Servlets and EJBs (and JSF page code etc).

The JPA objects are not, I believe, managed in this sense. So I think you would be back to pre-EJB3 techniques, doing JNDI lookup etc.

However as has been observed there may be some tangle in your hierarchy of responsibilities if you need to do this. It would be interesting if you posted a question about your overall design so that we could think about the design issues. My default position is that EJBs use JPA domain objects, JPA objects don't use EJBs.

djna
Looks like you're right: beans are managed (instantiated) by the container. http://docs.jboss.org/weld/reference/1.0.0/en-US/html/intro.html#bean-definition I want to avoid JNDI lookups because of coupling. I'd prefer to inject the LoginAttemptRepository manually in the UserRepository.Injecting services into domain classes is not so uncommon with domain driven design, if I'm not totally wrong. I have a user object, which I want to ask about failed logins in the last x seconds. The login attempts are stored in a repository because this information is needed separate from a specific user.
deamon
In Java EE 6, the concept of "managed classes" is not limited to Servlet, EJBs, etc with CDI. There is no interaction between CDI and JPA though.
Pascal Thivent
A: 

You would typically not do this simply because domain objects come out of the database as opposed to the container and therefore injecting services isn't as straight forward.

This does not mean however that you should not do this.

You know what your system is meant to achieve and which other systems it interacts with. This knowledge will effect the decision I'd imagine.

See Active Record link. As I meanted in my comment typically small systems would choose this route.

JamesC
+2  A: 

In Java EE 6, CDI extends the concept of managed component to anything and EJB can be injected into a CDI managed bean (using the @Inject annotation). But while interaction between JPA and CDI has been considered, this has not been made part of the Java EE 6 specification(s). In other words, injection into a JPA entity is not possible.

See also

Pascal Thivent