Flushing the Session in Hibernate by R4R Team

We found in the Hibernate an exception is that objects using native ID generation are inserted when they are saved.

We can say that Except when explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data.

It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time when the Hibernate Transaction API is used, flush automatically using the explained routine, or never flush unless flush() is called explicitly. The last mode is useful for long running units of work, where a Session is kept open and disconnected for a long time.

sess = sf.openSession();
Transaction tx = sess.beginTransaction();
sess.setFlushMode(FlushMode.COMMIT); //it allow queries to return stale state

Student iz = (Student) sess.load(Student.class, id);

// it might return stale data
session.find("from Student as student left outer join student.kittens kitten");

// change to iz is not flushed!
tx.commit(); // flush occurs

During flush, an exception might occur (if a DML operation violates a constraint). Since handling exceptions involves some understanding of Hibernate's transactional behavior. Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush. 

So we need to go through the by default at the following points:

1. before some query executions
2. from org.hibernate.Transaction.commit()
3. from Session.flush()

The SQL statements are issued in the following order:

1. all entity insertions in the same order the corresponding objects were saved using Session.save()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions in the same order the corresponding objects were deleted using Session.delete()
7. An exception is that objects using native ID generation are inserted when they are saved.
Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!