Table of Contents

About

All entity operations are described in the chapter 3: Entity Operations of the specification

The following operations are possible:

  • PERSIST,
  • MERGE,
  • REMOVE,
  • REFRESH,
  • DETACH
  • FLUSH

This operations must be performed in a active persistence context.

Operation

Persist

A new entity instance becomes both:

  • and persistent (adds it to the context):

by invoking :

  • the persist method on it
  • or by cascading the persist operation.

Example

MyEntity e = new MyEntity();
// transaction starts
em.getTransaction().begin();
em.persist(e); 
e.setSomeField(someValue); 
em.getTransaction().commit();
// transaction ends: the row for someField is updated in the database

Merge

The merge operation allows for the propagation of state from detached entities onto persistent entities managed by the entity manager.

If X is a:

  • new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
  • detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
  • a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again). Example:

MyEntity notAttachedEntity = new MyEntity();
// transaction starts
em.getTransaction().begin();
MyEntity attachedEntity = em.merge(notAttachedEntity); 
notAttachedEntity.setSomeField(someValue); 
em.getTransaction().commit();
// transaction ends: the row for someField is NOT updated in the database because you used e in place of the copy e2.

Flush

The flush method can be used by the application to force synchronization.

Refresh

Synchronization to the database does not involve a refresh of any managed entities unless the refresh operation is explicitly invoked on those entities or cascaded to them as a result of the specification of the cascade=REFRESH or cascade=ALL annotation element value.

Detach

JPA - Detached Entity

Remove

JPA - Removed Instance

Documentation / Reference