Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot Persistence Context annotation

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

like image 633
Priyanka Singh Avatar asked Sep 08 '17 10:09

Priyanka Singh


1 Answers

@PersistenceContext – We need to understand how we are able to connect with the database using just simple annotation @PersistenceContext and what it is.

  1. Entities are managed by javax.persistence.EntityManager instance using persistence context.
  2. Each EntityManager instance is associated with a persistence context.
  3. Within the persistence context, the entity instances and their lifecycle are managed.
  4. Persistence context defines a scope under which particular entity instances are created, persisted, and removed.
  5. A persistence context is like a cache which contains a set of persistent entities , So once the transaction is finished, all persistent objects are detached from the EntityManager’s persistence context and are no longer managed.
like image 59
Sri9911 Avatar answered Oct 04 '22 09:10

Sri9911