Reputation: 101
I am new in Spring Boot and trying to create a basic REST example in Spring boot. I am taking help from Spring Boot REST example website to create a basic example.
Most of the things are clear to me but I am stuck with one annotation which is being used to fetch the data from the database with the code as below
package com.springbootrest.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import com.springbootrest.model.BookDetails;
@Transactional
@Repository
public class BookDetailsRepoImpl implements BookDetailsRepo {
@PersistenceContext
private EntityManager entityManager;
public List<BookDetails> listBookDetails() {
return (List<BookDetails>) entityManager.createQuery("FROM BookDetails").getResultList();
}
}
I don't understand how @PersistenceContext
is actually working - can anyone please explain?.
Upvotes: 10
Views: 22752
Reputation: 1307
@PersistenceContext – We need to understand how we are able to connect with the database using just simple annotation @PersistenceContext and what it is.
Upvotes: 12
Reputation: 1133
My answer comes after quite a few years but here goes .
this annotation @PersistentContext
works in conjunction with another bean defined in your application context:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
The way the two work together is that the PersistenceAnnotationBeanPostProcessor
will lookup the appropriate EntityManagerFactory to inject the entity manager where we have attributes annotated with @PersistenceContext
My understanding is based on the answers to this question: so question here
Upvotes: 1
Reputation: 3383
The @PersistenceContext annotation in your code is being used to indicate that the EntityManager must be automatically injected, in other words its lifecycle will be managed by the container running your application (which is a good thing). The other option would be having all required configurations provided by you (application managed) via different options, all of them cumbersome (config files or beans) and running the risk of tying your application to some environment-specific configuration (which is a bad thing).
Upvotes: 6
Reputation: 573
In Short or layman language, Its a space(just to say) where entities are managed using Entity Manager.
Upvotes: 0
Reputation: 55
@PersistenceContext is JPA standard annotation which gives you better control of which persistence context you are Injecting.
Upvotes: 2