Hibernate- Clear

Hibernate- Clear

  • void evict(Object object) : Remove this instance from the session cache.

  • void clear() : Completely clear the session.

  • Void close() : close the session

Example

SQL> SELECT * FROM EMPLOYEE; 
     EMPNO EMPNAME              EMPDEPT
---------- -------------------- --------------------
         2 Sree                 R&D
         1 Kalyan               Developement


Clear () :

When this method get called inside transaction boundry then all objects which are currently associate with particular session will be disconnected / clean or no longer associate with that Session instance.

 Employee emp1 = (Employee) session.get(Employee.class, 1);
 Employee emp2 = (Employee) session.get(Employee.class, 2);
 // emp1 and emp2 are in persistent state.

 emp1.setEmpName("NEW SREE");
 emp2.setEmpName("NEW KALYAN");

 session.clear();
 // emp1 and emp2 are in detached state.

 session.getTransaction().commit();
 session.close();
     EMPNO EMPNAME              EMPDEPT
---------- -------------------- --------------------
         2 Sree                 R&D
         1 Kalyan               Developement

Therefore, after calling this method nothing will be performed on persistence layer or DB.


evict():

Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

        Employee emp1 = (Employee)session.get(Employee.class, 1);
        Employee emp2 = (Employee)session.get(Employee.class, 2);
        //emp1 and emp2 are in persistent state.
        
        emp1.setEmpName("NEW KALYAN"); // it will removed
        emp2.setEmpName("NEW SREE");
        
        session.evict(emp1);
        //emp1 is in detached state and emp2 is in persistent state.
        
        session.getTransaction().commit();
        session.close()

     EMPNO EMPNAME              EMPDEPT
---------- -------------------- --------------------
         2 NEW SREE              R&D
         1 Kalyan                Developement


Close()

Close session by calling session.close() method, means End the session and releasing the JDBC Connection and clean up.