Wednesday, June 12, 2013

23 - Understanding-State-Changes



We'll understand some of the different ways in which entity objects change from one state to another.

Transient State:  An object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).
A new instance of a a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate.
e.g.
UserDetails user = new UserDetails();
user.setUserName("Car");

Persistent State: A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.
A persistent instance has a representation in the database, an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session.
e.g. UserDetails user = (UserDetails) session.save(user);

Detached State: If we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to a Session anymore (but can still be modified and reattached to a new Session later though).
    A detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user. 





No comments:

Post a Comment