Hibernate : Flushing Session
In this section we will discuss about Hibernate session.flush().
Hibernate Session.flush() :
At any time during the processing of objects, we can call flush() method on
the session object. When you call flush at execution time, all queued SQL
statements are executed.
The Order of issuing SQL statements -
- all entity insertions in the same order the corresponding objects were saved using Session.save()
- all entity updates
- all collection deletions
- all collection element deletions, updates and insertions
- all collection insertions
- all entity deletions in the same order the corresponding objects were deleted using Session.delete()
When you persist or update an object, the work doesn't automatically occur in
the database, this is part of Hibernate's caching mechanism.
whenever you call flush() method, all the SQL statements are executed. You can
call flush() method any time.
Hibernate executes flush automatically when commit() method is called.
Example :
package net.roseindia.main; import net.roseindia.table.Student; import net.roseindia.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; public class HibernateSessionFlush { public static void main(String args[]) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; Integer roll = null; try { transaction = session.beginTransaction(); for (int i = 1; i <= 50; i++) { roll = i; String name = "Student" + i; String course="Course" + i; Student student = new Student(roll,name,course); session.save(student); if (i % 5 == 0) { session.flush(); session.clear(); } } transaction.commit(); session.close(); } catch (HibernateException e) { e.printStackTrace(); } } }