Entity Management

  1. How to make/ask Spring to manage an entity for you (i.e. avoid the use of EntityManagerFactory)
  2. How to operate the Entity Manager (Entity Operations)
  3. When does an entity become detached
  4. How to merge/re-attach an entity with an entity manager

Architecture Overview

How/Where an Entity Fits Overall

DAO Helper Library Usage

Entity Manager

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. This interface defines the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.  The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

To gain a better undestanding of JPA and Spring Enity Management, Please See: 

Three options for JPA setup in a Spring environment

This section describes the EntityManager operations for managing an entity instance’s lifecycle. An entity instance may be characterized as being new, managed, detached, or removed.

  • A new entity instance has no persistent identity, and is not yet associated with a persistence context.
  • A managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.
  • A detached entity instance is an instance with a persistent identity that is not (or no longer) associated with a persistence context.
  • A removed entity instance is an instance with a persistent identity, associated with a persistence context, that is scheduled for removal from the database.

And a graphical illustration:

JPA State Transitions

Best Practices & How To's

EntityManager Recommendation: LocalContainerEntityManagerFactoryBean

  • EntityManager Recommendation: LocalContainerEntityManagerFactoryBean
  • We recommend the following entity manager factory: LocalContainerEntityManagerFactoryBean See: LocalContainerEntityManagerFactoryBean
    • The most powerful of the three options
    • Can be used to specify dynamic declarative configs rather than using persistence.xml as we have done so in the template
    • Can specify/inject a loadTimeWeaver, dataSource, JPA Vendor via Spring
  • Please See Spring DAO Template provided

@PersistenceUnit vs @PersistenceContext: which to use

  • @PersistenceUnit vs @PersistenceContext: which to use
    • @PersistenceUnit annotation is used in J5SE applications to handle Java Persistence API (JPA) persistence management. You may use a PeristenceUnit in an application inside a container, but it must be managed by the developer instead of the container.
    • @PersistenceContext annotation is used for Container Managed Persistence (CMP). This relieves the developer of having to worry about connection management.
    • Recommendation: use @PersistenceContext when using Spring
      • Spring will do the hard work on your behalf
      • *
        ...
        /**
        * DAO to manage Fund entities.
        * 
        */
        @Repository("FundDAO")
        public class FundDAOImpl extends AbstractJpaDao implements FundDAO {
        
        /**
        * EntityManager injected by Spring for persistence unit costshare_pu_02
        *
        */
        @PersistenceContext(unitName = "costshare_pu_02")
        private EntityManager entityManager;
        
        ...
        }
        ... 
        *
        

EntityManager Operations

  • EntityManager Operations: See: Managing Entities
    • persist method: Persisting an Entity
    • find method: Finding an Entity
    • remove method: Removing an Entity
    • merge method: updating an Entity (different ways to do this)
    • Cascading Operations 
      • Entities that use relationships often have dependencies on the existence of the other entity in the relationship. For example, a line item is part of an order, and if the order is deleted, then the line item should also be deleted. This is called a cascade delete relationship
    • clear method: Clearing the Persistence Context of all entities

EntityManagerFactory vs EntityManager

  • EntityManagerFactory vs EntityManager: 
    • EntityManager: whenever using spring avoid managing/using EntityManagerFactory since Spring manages concurreny for you.
    • The entity manger injected by @PersistenceContext is thread safe.
    • While EntityManagerFactory instances are thread-safe, EntityManager instances are not. The injected JPA EntityManager behave just like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification. It will delegate all calls to the current transactional EntityManager, if any; else, it will fall back to a newly created EntityManager per operation, making it thread-safe.
    • See Spring Docs: The pros and cons of injecting EntityManagerFactory vs EntityManager are all spelled out.

EntityManager and Transaction Manager

  • EntityManager and Transaction Manager:
    •  The persist, merge, remove, and refresh methods MUST be invoked within a transaction context when an entity manager with a transaction-scoped persistence context is used. If there is no transaction context, the javax.persistence.TransactionRequiredException is thrown.

When does an entity become detached

  •  Detached Entity
    • An entity that is no longer associated with a persistence context is considered detached.
      • i.e. it used to be managed but no longer because of various reasons and hence will be persisted to the data-base base unless it is merged (opposite of detachment) again
  • An object can be detached intentionally or automatically
    • here are the most common situations:
      • When the entity is serialized 
        • for example entity sent to a jsp view via the Spring Controller
      • When calling EntityManager's detach() method
      • When a transaction roll-back occurs
      • When calling EntityManager's clear() method
      • When applicaiton-managed persistence context is closed, all its managed entities become detached
      • When the transaction that a transaction scoped persistence context is associated with commits, all the entities managed by the persistence context become detached.
      • ...
  • Merging: opposite of detachment, please see Merge

Recommended implementation/Usage

  • Recommended Architecture, See: Skyway Spring Tools Maven Repository for the Latest Release
    • See: DAO layer in the Architecture image
    • We are adopting a modified version of the open source Skyway Software Spring JPA Tools library (skyway-spring-utils-X.x.x.jar)
      • Namely we encourage using org.skyway.spring.util.dao.JpaDao and org.skyway.spring.util.dao.AbstratctJpaDao
      • note: modify AbstratctJpaDao and remove all @Transactional annotations since we are annotating our Service Layer rather than the DAO layer with @Transactional
      • make yourDAO extend the JpaDao interface
      • make yourDAOImpl extend the AbstratctJpaDao class
      • use the wrapper methods from theses 2 classes when possible
        • see class definitions for a list of available methods

References