Saturday, June 11, 2016

What is the difference among session.evict(),session.clear() and session.close()?

In Hibernate we have two kinds of cache first level and second level, for the first level cache will be associated with the session object of hibernate.where we are going to store the retrieved object from the data base for further use in the application.
For some scenario we have to remove those persisted object from the session object, to do that we have to use the following session methods.

  1. session.evict()
  2. session.clear()
  3. session.close()
Session.evict() :
  • Session.evict() method is used to remove the single object from the session.
           Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove only one  student object obj1 from session cache, we have to use the session method evict()

          session.evict(obj1); //Here we are removed obj1 object from session object
session.clear()
  • session.clear() method is used to remove all the persisted objects from the session first level cache.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove both   student objects obj1 and obj2 from session cache, we have to use the session method clear().

          session.clear(); //Here we are removed obj1  and obj2 object from session object

session.close()
  • session.close() method is used to close the session object associated with the session factory, which is no more exits to perform the data base operation using the persistent class and first level cache also automatically not available.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache. If you  close the session object  both   student objects obj1 and obj2 from session cache will be deleted along with the session object, we have to use the session method close().

          session.close(); //Here we are closing session object, simultaneously both obj1 and obj2 also removed from the session.




           

No comments:

Post a Comment