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?

5
  • I know but why is it happening? Commented Mar 17, 2015 at 15:54
  • What's lazzy fetching? A new feature? Commented Mar 17, 2015 at 15:56
  • @BoristheSpider here is an answer stackoverflow.com/questions/2990799/… Commented Mar 17, 2015 at 15:58
  • @gotchha that seems to be about lazy fetching... (don't worry, I was just being facetious). Commented Mar 17, 2015 at 15:59
  • @Boris It's fuzzy fetching, but with a lasso. Commented Mar 17, 2015 at 16:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

so is it like caching?
Kind of, if you think of your entities as the cache.
is there any solution to prevent it?
Re-fetching the entity from a new transaction will start over the lazy fetching, but the values might still come from the Hibernate cache. Is there any reason why you would want to fetch that data on every access? If you're worried about stale data, use optimistic locking with a version column.
thnx for your reply. I was just checking that session is closed properly or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.