Hibernate: Refresh, Evict, Replicate and Flush
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.
replicate()
is intended to be used instead of save()
/persist()
when you need to save an entity with a given identifier despite the fact that identifier of the said entity is configured to be generated.
It's useful when some of the entities (perhaps coming from external systems) have pre-existing identifiers, whereas other entities of the same type need their identifiers to be generated.
However, due to a long-standing bug in Hibernate (HHH-1459, HHH-2716) replicate()
doesn't work as expected with some kinds of id generators. This problem limits usefullness of replicate()
and requires you to implement unpleasant workarounds to emulate its behaviour if your id generator strategy is affected and you cannot change it.
-
session.flush()
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database. -
session.evict()
Detach the object from session cache. After detaching the object from the session, any change to object will not be persisted. -
session.refresh()
Reload all the data. -
session.replicate()
Data is replicated in different Datastore in different modes.