Any time an object passes through the Session instance, it's added to the Session�s cache. By passes through, we're referring to saving or retrieving the object to and from the database. To see whether an object is contained in the cache, call the Session.contains()method. Objects can be evicted from the cache by calling the Session.evict() method. Let's revisit the previous code, this time evicting the first Event instance:
Session session =factory.openSession();
Event firstEvent =(Event)session.load(Event.class,myEventId);
//...perform some operation on firstEvent
if (session.contains(firstEvent)){
session.evict(firstEvent);
}
Event secondEvent =new Event();
secondEvent.setId(myEventId);
session.save(secondEvent);
The code first opens the Session instance and loads an Event instance with a given ID. Next, it determines whether the object is contained in the Session cache and evicts the object if necessary. The code then creates a second Event instance with the same ID and successfully saves the second Event instance.
If you simply want to clear all the objects from the Session cache, you can call the aptly named Session.clear()method.