0

I have configured my userDetails class with lazy fetching, and I have also configured my settings for lazy fetching. I am running this code:

 userDetails user = new userDetails();

    user.setUserName("Fenil");

     Address address = new Address();
     address.setCity("baroda");
     address.setState("gujarat");
     user.getListOfAddress().add(address);

    SessionFactory sessionfactory = new          
    Configuration().configure().buildSessionFactory();
    Session session = sessionfactory.openSession();
    session.beginTransaction();

    session.save(user);
    system.out.println(user.getName()); //sop1
    session.getTransaction().commit();
    session.close();
    system.out.println(user.getName());  //sop2

When I run the code above it gives me the value of username. But, if I replace sop line right after session.close() then it's throwing an exception.

My question is:

If I print the sop1 line before closing the session it should give me the username, and after closing the session the line marked sop2 should throw an exception, but instead it's returning the value of username. Why?

Mark Bolusmjak
  • 23,606
  • 10
  • 74
  • 129
Dipesh Raichana
  • 1,008
  • 3
  • 18
  • 36

1 Answers1

1

Lazy fetching still fetches only once, storing the result for subsequent calls. During your second call, the data has already been fetched, so it can be returned even after the session was closed.

duckstep
  • 1,148
  • 8
  • 17