Database,  Java,  JPA,  Spring Framework

Java Persistence API (JPA) ~ Part 2 ~ Entity Manager

The entity manager API is used to create and remove entity instances, find entities by their primary key and to query entities.

JPA defines a persistence unit in the persistence.xml file which caters for:

  1. Caching
  2. Allowable operations
  3. Datasource
  4. Additional settings

From Spring 3.1, the persistence XML is not necessary because Spring scans the packages for all entities.

The LocalContainerEntityManagerFactoryBean supports a packagesToScan property.

The EntityManager supports database CRUD operations to persist objects to the database.

MethodDescription
getTransaction()Return the resource-level EntityTransaction object
persist(Object entity)Make an instance managed and persistent
remove(Object entity)Remove the entity instance
refresh(Object entity)Refresh the state of the instance from the database, overwriting changes made to the entity, if any
find(Class<T> entityClass, Object primaryKey)Find by primary key
createQuery(CriteriaDelete deleteQuery)Create an instance of Query for executing a criteria delete query
flush()Synchronize the persistence context to the underlying database

The relationship between JPA components:

Entities are considered to be in a managed state when managed by the EntityManager and until it is managed by the EntityManager it is just a POJO in a detached state.

This class uses JPA annotations without any Spring dependencies.

  • The @PersistenceContext annotation injects the EntityManager into the DAO class
  • By adding a single bean definition, the Spring container will act as a JPA container and inject an EntityManager from the EntityManagerFactory
  • This approach uses a transactional EntityManager, considered a shared EntityManager which is preferred to avoid creating a new EntityManager every time an operation has to be performed through the EntityManagerFactory.
  • This approach creates a shared thread-safe proxy, allowing the actual TransactionEntityManager to be injected instead of the factory.
  • The @PersistenceContext annotation has an optional attribute type property which defaults to PersistenceContextType.TRANSACTION which is required to receive a shared EntityManager proxy.
@Transactional
@Repository
public class ApplicationDAO implements IApplicationDAO {
   
   @PersistenceContext
   private EntityManager entityManager;

   @Override
   public void addApplication(Application application) {
       entityManager.persist(application);
   }

   @Override
   public Application getApplicationById(int applicationId) {
       return entityManager.find(Application.class, applicationId);
   }

Leave a Reply

Your email address will not be published. Required fields are marked *