简体   繁体   中英

How does lazy fetching work in Hibernate?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM