1.

What are the states of a persistent entity?

Answer»

A persistent ENTITY can exist in any of the following states:

Transient:

  • This state is the initial state of any entity OBJECT.
  • Once the instance of the entity class is created, then the object is said to have entered a transient state. These objects exist in heap memory.
  • In this state, the object is not linked to any session. Hence, it is not related to any database due to which any changes in the data object don't affect the data in the database.
InterviewBitEmployee employee=new InterviewBitEmployee(); //The object is in the transient state. employee.setId(101); employee.setFullName("Hibernate");  employee.setEmail("hibernate@interviewbit.com");

Persistent:

  • This state is entered whenever the object is linked or associated with the session.
  • An object is said to be in a persistence state whenever we save or persist an object in the database. Each object corresponds to the row in the database table. Any modifications to the data in this state cause changes in the record in the database.

Following methods can be used upon the persistence object:

session.save(record); session.persist(record); session.update(record); session.saveOrUpdate(record); session.lock(record); session.merge(record);

Detached:

  • The object enters this state whenever the session is CLOSED or the cache is cleared.
  • Due to the object being no longer part of the session, any changes in the object will not reflect in the corresponding row of the database. However, it would still have its representation in the database.
  • In case the developer wants to persist changes of this object, it has to be reattached to the hibernate session.
  • In order to achieve the reattachment, we can use the methods load(), merge(), refresh(), update(), or save() methods on a new session by USING the reference of the detached object.

The object enters this state whenever any of the following methods are CALLED:

session.close();session.clear();session.detach(record);session.evict(record);Persistent Entity


Discussion

No Comment Found