3

Newbie to Hibernate. I am just trying to understand session.get() method "avoiding a database hit if the object is already cached"

List<Employee> employees1 = session.createCriteria(Employee.class).list();

Main main = new Main();
try {
    synchronized (main) {
        main.wait(10000);
    }
} catch (InterruptedException e) {e.printStackTrace();}

Employee  employees2 = (Employee)session.get(Employee.class, new Long(1));
System.out.println(employees2.getFirstname() + " , "+ employees2.getLastname() );
  1. In the first line i got a record with firstname as 'Kevin' lastname as 'Papad'

  2. While it was waiting i went to database and changed firstname to 'steve'

  3. session.get() is not hitting database and getting me values firstname as 'Kevin' lastname as 'Papad' which is WRONG.

I kept wait because anybody can change values in database meanwhile (between 1st and 3rd steps above), in that case how can i get correct values in 3rd step? i.e., firstname to 'steve'

What changes do i need to make to my code?

Please correct me if my understanding/approach is wrong.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
Molay
  • 1,154
  • 2
  • 19
  • 42
  • The details can be understood from the thread http://stackoverflow.com/questions/8044963/hibernate-3-6-session-get-vs-session-load . The thread has pitfalls of get and load methods. – abhi Jul 02 '13 at 05:49
  • Moreover , hibernate session is not Threadsafe and as per api recomendation it is not advisable to keep the session open for long time , it should be opened and closed after each piece of work. – abhi Jul 02 '13 at 07:04

1 Answers1

0

You can call session.refresh(Object) with the entity you want to be reloaded. http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#objectstate-loading

Note: There is a warning in Javadoc about usage of this, see this thread for a discussion.

lunr
  • 5,159
  • 4
  • 31
  • 47
  • 1
    so, every time do i need to use session.refresh(Object) if i call session.get() ? – Molay Jun 14 '13 at 06:58
  • If you can't know whether that entity is loaded and you have to have the latest version of it, than i think yes. By the way you don't have to call `get()` in your example. You loaded the whole table with the first line. So you can just iterate over the list and check for the one with `id == 1`. – lunr Jun 14 '13 at 10:11