2

When load is called, Hibernate checks if the object is already contained in the session. If this is true, then the object is returned, otherwise a proxy is created.

Session is for interacting with the database, how it contains the object when passing the object in load method. Then what about proxy where it is used.

1
  • session is also the first level cache (in memory) for performance reasons. CGLIB proxies are created to facilitate lazy loading of entities/ collections.
    – aishwarya
    Dec 27, 2011 at 11:21

1 Answer 1

1

A proxy is just an envelope around a real object. When you call session.load(Person.class, 3), Hibernate will check if the Person with ID 3 is already in the session cache. If it's not, it will create a proxy, store it in the session cache, and return it. The proxy is a class which works like this:

public class PersonProxy extends Person {
    private int id;
    private boolean initialized = false;

    public String getName() {
        if (!initialized) {
            // read state of the entity from database;
            initialized = true;
        }
        return this.name;
    }

    ...
}
4
  • when session is closed,total first level cache is cleared or not? Dec 30, 2011 at 10:28
  • Yes. The first level cache is maintained by the session. If you close the session, its first-level cache is cleared.
    – JB Nizet
    Dec 30, 2011 at 10:32
  • if another thread is open a session,then the proxy is available or not?.If not where is the performance issue?.If if the Person with ID 3 session is not closed,is it available throughout the application? Dec 30, 2011 at 12:06
  • Each session has its own first-level cache, and its own copy of a given person (if loaded in this session). You should read the hibernate reference manual. It explains how everything works. And please accept answers to your questions when they solved your problem, and upvote them when they're useful.
    – JB Nizet
    Dec 30, 2011 at 12:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.