JPA EntityManager Operations

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We have seen about the types of EntityManagers in previous articles, this article deals with different  JPA EntityManager Operations.

JPA EntityManager operations:

There are three types of JPA EntityManager Operations:

  • Persisting an entity
  • Finding an entity
  • Removing an entity

Persisting an entity:

  • The  persist()  method of EntityManager accepts a new entity instance and makes it a managed instance.
  • If entity to be persisted is already managed, it is ignored.
  • Once entity becomes managed, modifications does in entity are traced by entitymanager.
  • persist()  operation is intended for new entities that do not already exist in the datdabase.

An example of persist() operations among all JPA EntityManager Operations is as below.

 Finding an Entity:

find()  operations is most commonly used among all JPA EntityManager Operations.

  • Whenever an entity needs to be located by primary key, find() method is used.
  • find() operation returns a managed entity instance in all cases except when it is invoked outside a transaction on a transaction scoped entitymanager.
  • In above case, the entity instance is returned in detached state and is not associated with persistence context.

An example of find operations is as below

Employee emp = em.find(Employee.class, empId);

This returns an instance of Employee class with provided empId which represents primary key value in database.

Removing an Entity:

remove()  operation among JPA EntityManager operations deletes the entity from database.

  • An entity can be removed by passing the entity to  remove()  method.
  • An entity can be removed only if it is being managed by persistence context.
  • When entity relationships are involved, then relationships should be removed explicitly.
  • Relationship maintenance is the responsibility of application.

Example below shows how to remove entities when relationships are involved.

This was all about JPA EntityManager Operations

 

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

One thought on “JPA EntityManager Operations

Leave a Reply

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