Please find the following code
Code:
//Get employee with id=1
userDetails emp = (userDetails) session.load(userDetails.class, new Integer(1));
printData(emp,1);
//waiting for sometime to change the data in backend
// Thread.sleep(10000);
session.flush();
//Fetch same data again, check logs that no query fired
userDetails emp1 = (userDetails) session.load(userDetails.class, new Integer(1));
printData(emp1,2);
//Create new session
Session newSession = sessionFactory.openSession();
//Get userDetails with id=1, notice the logs for query
userDetails emp2 = (userDetails) newSession.load(userDetails.class, new Integer(1));
printData(emp2,3);
//START: evict example to remove specific object from hibernate first level cache
//Get userDetails with id=2, first time hence query in logs
userDetails emp3 = (userDetails) session.load(userDetails.class, new Integer(2));
printData(emp3,4);
//evict the userDetails object with id=1
[color=#FF4000] session.evict(emp);[/color]
System.out.println("Session Contains Employee with id=1?"+session.contains(emp));
//since object is removed from first level cache, you will see query in logs
userDetails emp4 = (userDetails) session.get(userDetails.class, new Integer(1));
printData(emp4,5);
//this object is still present, so you won't see query in logs
userDetails emp5 = (userDetails) session.load(userDetails.class, new Integer(2));
printData(emp5,6);
//END: evict example
//START: clear example to remove everything from first level cache
session.clear();
userDetails emp6 = (userDetails) session.load(userDetails.class, new Integer(1));
printData(emp6,7);
userDetails emp7 = (userDetails) session.load(userDetails.class, new Integer(2));
printData(emp7,8);
System.out.println("Session Contains userDetails with id=2?"+session.contains(emp7));
when i evict the object from session using session.evict(emp); and again call
that object using userDetails emp4 = (userDetails) session.get(userDetails.class, new Integer(1)); (same primary key 1) that time its suppose to hit the database and find the record again but it returns the object from session(without hitting on DB) How ?? i found this using show sql.
can any one explain please am new to hibernate !