Surendra Royal
Surendra Royal

Reputation: 97

Can't understand the session in hibernate

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.

Upvotes: 2

Views: 136

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

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;
    }

    ...
}

Upvotes: 1

Related Questions