简体   繁体   English

懒惰获取在Hibernate中如何工作?

[英]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. 我已经用惰性获取配置了userDetails类,并且还配置了惰性获取的设置。 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. 但是,如果我在session.close()之后立即替换sop行,则会引发异常。

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. 如果我在关闭会话之前打印了sop1行,则应为我提供用户名,而在关闭会话之后,标记为sop2的行应引发异常,但它将返回用户名的值。 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. 在您的第二个呼叫期间,数据已被提取,因此即使在会话关闭后也可以将其返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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