The Hibernate Documentation gives good examples of this. Also this blog post will give you some insight. I will add some line from there below.
It is possible to re-load an object and all its collections at any time, using the refresh()
method. This is useful when database triggers are used to initialize some of the properties of the object.
sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)
see here for more examples.
Whenever you pass an object to save(), update() or saveOrUpdate()
, and whenever you retrieve an object using load(), get(), list(), iterate() or scroll()
, that object is added to the internal cache of the Session.
When flush()
is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur, or if you are processing a huge number of objects and need to manage memory efficiently, the evict()
method can be used to remove the object and its collections from the first-level cache.
ScrollableResult cats = sess.createQuery("from Cat as cat").scroll(); //a huge result set
while ( cats.next() ) {
Cat cat = (Cat) cats.get(0);
doSomethingWithACat(cat);
sess.evict(cat); // (if gives the compile time error then use it: sess.evict(cat.getClass());
}
Read the complete example from here.
Read about the session API here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…