Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @Inject and @PersistenceContext?

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.

like image 895
Thiago Chaves Avatar asked May 16 '13 22:05

Thiago Chaves


People also ask

What is the use of @PersistenceContext?

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.

What does @inject annotation mean?

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.

How does @inject annotation work?

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.

What is PersistenceContext in hibernate?

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.


1 Answers

@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.

like image 92
soschulz Avatar answered Oct 13 '22 00:10

soschulz