Question

In a project using JPA, I commonly use

@Inject EntityManager em;

in order to obtain such an object. I saw that many code snippets in the web instead use:

@PersistenceContext EntityManager em;

What is the difference between these options?

My code runs on JBoss EAP 6.1 and Hibernate.

Was it helpful?

Solution

@PersistenceContext is a specific annotation that declares a dependency on a container-managed entity manager. It allows you to specify more parameters like the persistence type. Setting the persistence type to EXTENDED is important when you want to maintain the persistence context for the whole life cycle of a stateful session bean. @PersistenceContext is a JPA annotation.

@Inject is a CDI annotation. It is very generic and can be used to inject a wide variety of objects.

OTHER TIPS

@PersistenceContext is a very specific annotation and it's saying "inject this field with a persistence context". You can't use it outside of a managed context.

@Inject on the other hand, is very generic. It says, "you should inject this field." It's not necessarily for a persistence context, but anything you want to define as injected.

This article (which is not exactly apples to apples of what you're asking) may shed more light on it for you.

If you want to go straight to the source of what @Inject is, you can read the spec here:

@Inject, identifies a point at which a dependency on a Java class or interface can be injected. The container then provides the needed resource. In this example, the Login bean specifies two injection points.

@Inject will provide you with what the container deems to be the EntityManager hopefully there is only one.

However, if you happen to have more than one you'd have to go through some qualifier annotations and have something producing it for you or you can pass in the unitName attribute to the @PersistenceContext annotation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top