Reputation: 672
I am new in Hibernate and JPA and I have problem with this annotation. Could someone explain me in simple words what this annotation actually doing, becouse documentation is hard to understand for me in this case.
EDIT I understand what Persistent Context is, but in code I have for example something like that:
@Repository
public class AbstractRepository<E extends Identifable> implements IRepository<E> {
private Class<E> clazz;
@PersistenceContext
protected EntityManager em;
And I have problem with what @PersistenceContext doing. Sorry, Maybe I was not specific.
Upvotes: 3
Views: 1726
Reputation: 1292
A PersistenContext is aware of your DataSource,JPA properties, Entities etc. As already described here: What is Persistence Context? You can use it to do some manual stuff in your repository. Eg. handle transactions. I used it a few times in older projects with horrible designed databases. Normally it should not be necessary. Spring can nearly handle everything if your database is designed well.
Maybe this helps you:
public void saveMovie() {
EntityManager em = getEntityManager();
em.getTransaction().begin();
Movie movie = new Movie();
movie.setId(1L);
movie.setMovieName("The Godfather");
movie.setReleaseYear(1972);
movie.setLanguage("English");
em.persist(movie);
em.getTransaction().commit();
}
https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa
https://www.baeldung.com/hibernate-entitymanager
If you don't need to do something special you can just define a repository interface without any implementation.
https://www.baeldung.com/spring-data-repositories
Upvotes: 1