Hibernate method flush flush() commit commit() clear clear()
Words explaination:
Flush
To clean, rinse, or empty with a rapid flow of a liquid, especially water
1. check the hibernate API
Session (Hibernate API Documentation)<!-- Generated by javadoc (build 1.4.2_09) on Mon Mar 20 14:19:10 CST 2006 --><script type="text/javascript"><!-- function windowTitle(){ parent.document.title="Session (Hibernate API Documentation)";}// --></script>
public void flush () throws HibernateExceptionForce the Session to flush. Must be called at the end of a unit of work, before commiting the transaction and closing the session (Transaction.commit() calls this method). Flushing is the process of synchronising the underlying persistent store with persistable state held in memory.Throws:
HibernateException
What this method do:Flushing is the process of synchronising the underlying persistent store with persistable state held in memory.
When to call the method:Must be called at the end of a unit of work, before commiting the transaction and closing the session.
2.
http://www.99inf.net/SoftwareDev/Java/53962.htm
以session的save方法为例来看一个简单、完整的事务流程,如下是代码片段:
…………………………………………………………………………
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(customer);//之前已实例化好了的一个对象
tx.commit();
…………………………………………………………………………
示例很简单,就是向 DB 中插入一条顾客信息,这是一个最简单的 DB 事务。
Hibernate: select max(ID) from CUSTOMER
Hibernate:insert into CUSTOMER (NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX,IS_MARRIED, description, BIRTHDAY, REGISTERED_TIME, ID) values (?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)
这里也许看不出什么端倪来,现在在session.save(customer)后面加一行代码,输出这个customer的OID,System.out.println(customer.getId()),再次运行程序,控制台输出为:
Hibernate: select max(ID) from CUSTOMER
22
Hibernate:insert into CUSTOMER (NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX,IS_MARRIED, description, BIRTHDAY, REGISTERED_TIME, ID) values (?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)
OID在insert语句之前输出,这可以说明两个问题:
1.insert语句并不是在执行save的时候发送给 DB 的;
2.insert语句是在执行commit的时候发送给 DB 的。结合前面我们所说过的:执行save的时候,Hibernate会首先把对象放入缓存,然后计划一条insert语句。一个基本的插入流程就出来了:
1. 判断所要保存的实例是否已处于持久化状态,如果不是,则将其置入缓存;
2. 根据所要保存的实例计划一条insert sql语句,注意只是计划,并不执行;
3. 事务提交时执行之前所计划的insert语句;
后台还打印出了select max(ID) from CUSTOMER,这主要是为了给customer赋予一个OID,因为一般情况下临时对象的OID是NULL。
接着我们做两个测试:
1. 将tx.commit();注释掉,此时控制台没有打印出insert语句;
2. 将tx.commit()换成session.flush,此时控制太打印出了insert语句,但是DB 中并没有添加新的记录;
通过查阅Hibernate的API可以知道
1. flush方法的主要作用就是清理缓存,强制数据库与Hibernate缓存同步,以保证数据的一致性。
2. 同时其主要动作就是向数据库发送一系列的sql语句,并执行这些sql语句,但是不会向数据库提交。
commit方法则会首先调用flush方法,然后提交事务。这就是为什么我们仅仅调用flush的时候记录并未插入到数据库中的原因,因为只有提交了事务,对数据库所做的更新才会被保存下来。因为commit方法隐式的调用了flush,所以一般我们都不会显示的调用flush方法。