Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How does Hibernate implement lazy loading for a @ManyToOne association and for a collection? What consequences does the proxy have for code like order.getCustomer().getClass() or instanceof checks?

For a lazy @ManyToOne, Hibernate puts a generated proxy subclass of the target entity in the field, which knows only the id and loads the row the first time we call a non-id method. For a lazy collection, it uses its own collection wrappers such as PersistentBag or PersistentSet, which load on first access. Because a proxy is a different class, getClass() returns the proxy class, an equals based on getClass fails, and a proxy of a base class is not an instance of the actual subclass; Hibernate.getClass and Hibernate.unproxy give the real class or object.

Why this question is asked

Lazy loading feels like magic: we access order.getCustomer().getName() and the data is there, although no query loaded it earlier. Knowing how the trick works explains several bugs that otherwise look impossible, such as an equals that returns false for the same row, or an instanceof check that says a Dog is not a Dog. Interviewers ask this internals question because those bugs are common and the fixes depend on understanding the mechanism. In this answer, we will see how Hibernate makes a @ManyToOne lazy, how lazy collections work, and then the consequences for getClass, equals, instanceof and id access.

1Lazy @ManyToOne: The Proxy

When Hibernate loads an Order whose customer association is LAZY, the orders row already contains customer_id = 17. Hibernate does not query the customer table. Instead it creates an instance of a class it generated at runtime, using the ByteBuddy library, that extends Customer. This object is a proxy: it holds the id 17 and a small helper called the lazy initializer, and its own Customer fields are all empty.

Every method on the proxy is intercepted. If we call getId(), the interceptor answers from the id it already knows, without a query. If we call getName(), the interceptor notices the proxy is not initialized, asks the session to load customer 17, keeps a reference to the real Customer object it gets back, and forwards the call to it. From then on, every call goes to that real object.

Java
Order order = em.find(Order.class, 1L); // select ... from orders where id = 1
Customer c = order.getCustomer(); // no query: c is a proxy
System.out.println(c.getClass().getSimpleName()); // Customer$HibernateProxy$Lk3sP2aQ (name varies)
System.out.println(c.getId()); // 17, no query
System.out.println(Hibernate.isInitialized(c)); // false
System.out.println(c.getName()); // select ... from customer where id = 17 -> "Asha Rao"
System.out.println(Hibernate.isInitialized(c)); // true
Step throughCalling getName() on an uninitialized proxy
Our codeCustomer proxySessionDatabase
getId()
17, no query
getName()
initialize customer 17
select from customer where id = 17
row
real Customer object
"Asha Rao" from the real object

8 messages in order. Play them, or step through them one at a time.

Notice that the proxy stays a proxy even after initialization. The field in Order still holds the proxy object, which now delegates to the loaded Customer. That detail is the source of the getClass problems below.

2Lazy Collections: Persistent Wrappers

Collections are not proxied with a subclass. When Hibernate loads an Order with a lazy List<OrderLine> lines, it places its own implementation of List in the field, a PersistentBag for a List without an order column, PersistentList for one with an order column, PersistentSet for a Set and PersistentMap for a Map. The wrapper knows its owner and its role, for example Order.lines of order 1, but holds no elements yet.

The first operation that needs the elements, such as size(), iterator() or get(0), makes the wrapper ask the session to load them, with a query like select ... from order_line where order_id = 1. The wrapper also tracks changes, which is how Hibernate knows at flush time which lines were added or removed. This is also why we should modify the managed collection rather than replace it with a new ArrayList.

Java
System.out.println(order.getLines().getClass().getSimpleName()); // PersistentBag
System.out.println(Hibernate.isInitialized(order.getLines())); // false
System.out.println(order.getLines().size()); // select ... from order_line where order_id = 1 -> 3

3Consequence 1: getClass() and equals

Since the proxy is a subclass, getClass() on it returns the generated class, not Customer. Any equals written as if (getClass() != o.getClass()) return false will say that a loaded Customer and a proxy for the same row are different. Reading fields directly from the other object fails too, because the proxy's own fields are null; the data lives in the target object behind it.

Java
Customer loaded = em.find(Customer.class, 17L); // may already be the proxy if it is in the session
Customer ref = otherOrder.getCustomer(); // a proxy for 17 from another path
System.out.println(ref.getClass() == Customer.class); // false
System.out.println(Hibernate.getClass(ref)); // class com.shop.Customer (initializes the proxy)
Customer real = (Customer) Hibernate.unproxy(ref);
System.out.println(real.getClass() == Customer.class); // true

So equals on entities should use instanceof or compare effective classes, and read the other object's id through its getter. Hibernate.getClass returns the real entity class and Hibernate.unproxy returns the real object; both initialize the proxy if needed. Note that within one session, Hibernate returns the same instance for the same row, so if a proxy for customer 17 was created first, a later em.find may hand back that same proxy.

4Consequence 2: instanceof With Inheritance

The second trap appears with entity inheritance. Suppose Pet is an entity with subclasses Dog and Cat, and Owner has @ManyToOne(fetch = LAZY) Pet pet. When Hibernate creates the proxy, it only knows the row's foreign key, not which subclass the row is, so it generates a proxy of Pet. That proxy is not a Dog, even if the row is a dog.

Java
Pet pet = owner.getPet(); // proxy of Pet
System.out.println(pet instanceof Dog); // false, even for a dog
Pet real = (Pet) Hibernate.unproxy(pet);
System.out.println(real instanceof Dog); // true
Dog d = (Dog) pet; // ClassCastException
Proxy behaviour summary
Operation on an uninitialized proxyResult
getId()returns the id, usually no query
any other getterloads the row, then delegates
getClass()the generated proxy class
direct field read from outsidenull, fields live in the target
instanceof actual subclassfalse, proxy extends the base class
Hibernate.unproxy(p)the real object, loading it if needed

The fixes are to unproxy before type checks, to fetch the association with a join so Hibernate builds the real subclass instance, or better, to avoid instanceof by putting behaviour in the entity, such as a polymorphic method on Pet that each subclass overrides, which the proxy forwards correctly.

5Consequence 3: Accessing Only the Id

Because the proxy knows its id, code that only needs the id of an association, for example to build a link or compare ids, can call order.getCustomer().getId() without loading the customer. This usually holds, but there are details: with a JPA compliance setting for proxies, or certain access types, behaviour can differ, so check your version and confirm in the SQL log. When an id is all we need, mapping the foreign key column also as a read-only basic attribute, or selecting it in a DTO query, avoids the question entirely.

6Follow-up questions

What does em.getReference() return?

It returns a proxy for the given id without querying, the same kind of object a lazy @ManyToOne holds. It is useful for setting an association when we know only the id, for example order.setCustomer(em.getReference(Customer.class, 17L)), which saves a select. If the row does not exist, the error appears only when the proxy is initialized.

Why does accessing a proxy after the transaction fail?

Initialization needs an open session to run the query. Once the transaction and its persistence context are closed, the entity is detached, and the proxy's initializer has no session to use, so it throws LazyInitializationException. The same applies to lazy collection wrappers.

Can entity classes be final?

Not if we want lazy proxies, because the proxy must subclass the entity, and the methods that need intercepting must not be final either. Hibernate falls back to eager loading or reports a problem for final classes depending on the version, so entities are normally non-final with non-final getters.

7Conclusion

In this answer, we saw that a lazy @ManyToOne is a runtime-generated proxy subclass that knows only the id and loads the row on the first call to another method, and that lazy collections are Hibernate's persistent wrappers that load on first access and track changes. Because proxies are subclasses, getClass() returns the proxy class, field-based equals fails, and a base-class proxy is not an instance of the real subclass, so we use getters, instanceof, Hibernate.getClass or Hibernate.unproxy.

What to say in the interviewAbout 90 seconds aloud

Open with

For a lazy @ManyToOne, Hibernate already has the foreign key from the owner's row, so instead of querying it creates a proxy, a subclass of the target entity generated at runtime with ByteBuddy, holding just the id and a lazy initializer.

Then, if they want more

Calling getId on it returns the id, usually without a query. Calling any other method makes the initializer load the row through the session and then delegate the call to the real object; the field keeps pointing at the proxy.

For collections, Hibernate does not subclass anything; it puts its own collection implementations in the field, PersistentBag for a plain List, PersistentSet, PersistentList with an order column, and those load their elements the first time we call size, iterate and so on, and also track changes for the flush.

The consequences: getClass on a proxy returns the proxy class, so an equals using getClass, or reading fields directly from the other object, fails for a proxy of the same row; I use instanceof and getters, or Hibernate.getClass.

With inheritance, a lazy reference typed as the base class is a proxy of the base class, so instanceof Dog is false even when the row is a dog; Hibernate.unproxy or a fetch join gives the real subclass, or better, polymorphic methods avoid the check. And everything fails with LazyInitializationException once the session is closed.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does Hibernate implement lazy loading for a @ManyToOne association and for a...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/9d807eff8c/