Tuesday, February 1, 2011

Hibernate Object States

Hibernate has three object states that has been stated below.

                * If Object is transient, instance has just been instantiated with new Operator and it's not associated with Hibernate Sesssion. It has no persistance representation in database and no identifier value has been assigned.

                * Transient object will be garbage collected if application doesnt have any reference any more. Use the Hibernate session to make an Object persistent.


                * A persistance instance has a representation in database and an identifier value. It might have been just saved or loaded. It will be associated with a hibenate 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.


              * A detached instance is persistence but its session is closed. It will be modified in the current state if the reference of the object is valid.
             * A detached instance can be reattached to a new session and maing it persistent again.

what will do load(), get() and referesh() method?

load() method is used to retrive the persistence instance if we know the identiifier value. It will throw an unrecoverable exception if there is no matching database row. load() methods of Session used to take an Object Class and loads to the new Instatantiated instatance.

get() method will not throw an any exception if there is no matching database row. Simply it will return null.

reload() method used to re-load an object and all its collections at any time. This is useful when database triggers are used to initialize some of the properties of the object.

What will do the persistent() and save() methods?

persistent() method is used to makes transient instance persistent. it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. It will not execute the INSERT statement if it is called outside of the transanctions boundaries.
It violates the NOT NULL constraint upon a foreign key.

Save() method will return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction.

It will not violate a NOT NULL constraint.