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.
You can use the @PersistenceContext annotation to inject an EntityManager in an EJB 3.0 client (such as a stateful or stateless session bean, message-driven bean, or servlet). You can use @PersistenceContext attribute unitName to specify a persistence unit by name, as Example 29-13 shows.
The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms. Bean constructor parameter injection: public class Checkout { private final ShoppingCart cart; @Inject.
Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.
The persistence context is the first-level cache where all the entities are fetched from the database or saved to the database. It sits between our application and persistent storage. Persistence context keeps track of any changes made into a managed entity.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With