2014/01/14

Difference between commit and flush in Hibernate

★★★Q:
Transaction t = session.beginTransaction();
session.update(item);
t.commit();
-------------------------------------------
session.update(item);
session.flush();

----------------------------------------------
i found out that they basically does the same thing

so what is Difference between commit and flush in Hibernate?

★★★A:
・Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory
・The flush process synchronizes database state with session state by detecting state changes and executing SQL statemen

★★★テスト
//set the JDBC batch size (it is fine somewhere between 20-50) 
hibernate.jdbc.batch_size 30 
 
//disable second-lavel cache 
hibernate.cache.use_second_level_cache false 
 
//and now do your job like this 
Session S=SF.openSession(); //SF = SessionFactory object 
Transaction T=S.beginTransaction(); 
    
for (int i=0;i<200000;i++) 

   record r=new record(...); 
   S.save(record); 
   if(i % 30==0) 
   {     
      //30, same as the JDBC batch size 
      //flush a batch and release memory 
      session.flush(); // Line 1 
      session.clear(); 
   } 
}  
//clean   
T.commit(); // Line 2 
S.close(); 
==ー>
My test tells me the session.flush() does not make the data visible to other clients. It is available only after the commit.
And I also notice when I set the batch size from 10, 100, 1000, 10000, the performance is pretty much the same. 1%-2% difference with
each other.