Session flush is the process of synchronizing the underlying persistent store with persistable state held in memory. Flushing the session simply gets the data in the session synchronized with the database. If a persisted object in the Session has value change, it becomes dirty, and Session flush will update the database in the running transaction, but it may not commit those changes.
The behavior of the flushing mechanism is customizable, and a Session can set to different Flush Modes:
- AWAYS – the Session is flushed before every query
- AUTO – the Session is sometimes (when it is necessary) flushed before query execution in order to ensure that queries never return stale state. It is the default mode.
- COMMIT – the Session is flushed when Transaction.commit() is called.
- MANUAL – the Session is only ever flushed when Session.flush() is explicitly called by the application. This mode is very efficient for read only transactions.
Commit is a method of Hibernate Transaction interface, it will flush the associated Session and make the database commit (when Session is in FlushMode.MANUAL).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public void saveWithLessMemoryRequirement() { try { HibernateUtil.beginTransaction(); for (int i = 1; i < 2000000; i++) { UserAccount userAccount = new UserAccount(); userAccount.setAddr1("2150 Zanker Road"); userAccount.setAddr2("suite " + System.currentTimeMillis()); userAccount.setCity("San Jose"); userAccount.setCountry("USA"); userAccount.setFirstname("Lefang"); userAccount.setLastname("Hongaria"); userAccount.setPhone("4088689917"); userAccount.setState("CA"); userAccount.setUsername("pdn" + System.nanoTime()); userAccount.setZipcode("95134"); HibernateUtil.getSession().save(userAccount); if (i % 50 == 0) { // like batch process HibernateUtil.getSession().flush(); // flush batch HibernateUtil.getSession().clear(); // clear memory } } HibernateUtil.commitTransaction(); } catch (Exception ex) { HibernateUtil.rollbackTransaction(); throw new RuntimeException(ex); } finally { HibernateUtil.closeSession(); } } |