Wednesday, December 30, 2015

Entity States

Java applications contain a mix of transient and persistent objects. Transient (or normal objects) has a limited lifetime and is bounded by life of the process that instantiated it.  But persistent objects (or Entity) can be stored on disk or file system to create again in the future. 

The Java Persistence API (JPA) is part of EJB 3.0 specification (EJB 3.0 itself is part of Java Enterprise Edition). JPA refers to persisted or persistable  classes as Entity.  Technically, it's  just a POJO class which maps to a database table/view. Instance of an entity can represent a single row of a table. This post will cover different states an instance of an Entity could be in. In context of JPA, object and entity refers to the same thing (more details here)

Entity States 

  1. New/Transient Object which got instantiated using new operator is in transient state as it's not yet associated with any persistence context. It's not mapped yet to a record/row in database. It's just another object; and in fact JPA specification doesn't give any name for this state. 
  2. Managed/Persistent Object has a database identity. This means the instance has a valid primary key value to uniquely identity it in the database (or more specifically in a table). These instances are associated with a persistence context. 
  3. Detached As long as persistence context is active entity is in managed state. Once transaction (or unit of work) completes, persistence context is closed but the application still has handle to the entity. So such entities are in detached state. 
  4. Removed During the transaction we can delete or remove an entity. It's still associated with persistence context but it get's scheduled for deletion (at the end of transaction). So a removed object shouldn'd be reused and any reference holding it should be discarded. 
Image Reference : http://openjpa.apache.org

Let's Code

Let's code to explain the above states:

New

Student student = new EngineeringStudent();
student.setName(..);
student.setGrade(..);
student.setXX(..);

Managed

entityManager.persist(student);    //JPA
session.save(student);                  //Hibernate 

Delete
session.delete(student);
entityManager.remove(student);

Detached
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

Student student = fetchStudentWithIdFromDb(id);
student.setGrade(..);
tx.commit();
session.close();

student.setXX(..);   //student is detached here

Detaching Inside a transaction
session.evict(student);  //detaches one object
session.clear(); //detaches all objects

No comments:

Post a Comment