What does the Hibernate proxy object contain?

All I could gather from Google is that:

  • Hibernate uses a proxy object to implement lazy loading. When we request to load the Object from the database, and the fetched Object has a reference to another concrete object, Hibernate returns a proxy instead of the concrete associated object.

  • Hibernate creates a proxy object using bytecode instrumentation (provided by javassist). Hibernate creates a subclass of our entity class at runtime using the code generation library and replaces the actual object with the newly created proxy.

So, what exactly does the Proxy object contain?

Does it contain a skeleton object reference object with only the id field set? Others field will be set when we call the get method?

Does the Proxy object contain the JDBC statement to fetch all data required to fully populate the referenced object.

Is there something else I might be missing?

I am not asking for spoon feeding but if you can provide any link with information that would be great.

Any correction to above description will also be welcomed.

Example.

class Address {
   String city;
   String country;
}

class Person{
   int id;
   String name;
   Address address;
}    

When we try to load the Person object, Hibernate will subclass Person class like:

class ProxyPerson extends Person {
       int id;
       String name;
       Address proxyCGLIBObject;
}

and return a ProxyPerson object. Object of ProxyPerson will have a value for id and name but proxy for Address.

Am I correct?

What can I expect from adding a toString() method on the proxy object?


Solution 1:

The Hibernate Proxy is used to substitute an actual entity POJO (Plain Old Java Object).

The Proxy class is generated at runtime and it extends the original entity class.

Hibernate uses Proxy objects for entities is for to allow [lazy loading][1].

When accessing basic properties on the Proxy, it simply delegates the call to the original entity.

Every List, Set, Map type in the entity class is substituted by a PersistentList, PersistentSet, PersistentMap. These classes are responsible for intercepting a call to an uninitialized collection.

The Proxy doesn't issue any SQL statement. It simply triggers an InitializeCollectionEvent, which is handled by the associated listener, that knows which initialization query to issue (depends on the configured fetch plan).