Convert a Hibernate Proxy to a Real Entity Object
In this article
A Hibernate proxy is a runtime-generated subclass that stands in for a persistent entity so the framework can defer loading it until a field is actually touched. Converting that proxy to a real entity object means replacing the placeholder with an instance of the actual mapped class, so that getClass() returns the entity type, instanceof checks behave as expected, and the object can be serialized, cached, or passed outside the persistence context without surprises. The standard way to do this is to ask Hibernate to unwrap the proxy, either through its built-in unproxy utility or by initializing the proxy first and then copying state into a fresh instance.
Nothing here requires special libraries beyond Hibernate itself and a working SessionFactory or EntityManagerFactory. The main prerequisite is understanding that a proxy only exists while its owning session is open and the entity was loaded lazily (typically through a @ManyToOne, @OneToOne, or session.load() call).
What You'll Need
- Hibernate Core (or Hibernate ORM via Spring Data JPA) on the classpath, version 5.2 or later for the modern
unproxyAPI. - An open
SessionorEntityManagerthat owns the proxy, or a way to reattach the entity. - The concrete entity class you expect the proxy to represent.
- A basic understanding of lazy versus eager fetching in your mappings.
Step-by-Step
- Confirm the object is actually a proxy. Call
Hibernate.isInitialized(entity). If it returnsfalse, the object is an uninitialized proxy; iftrue, it is either a real instance or an initialized proxy. You can also inspectentity.getClass().getName()and look for a$$EnhancerByHibernateor_$$_jvstsuffix, which indicates a generated subclass. - Get hold of the owning session. Use
sessionFactory.getCurrentSession(), an injectedEntityManager, orentityManager.unwrap(Session.class). The unwrap call fails if the session is closed or if you are outside a transaction, so make sure you are inside one. - Call Hibernate's unproxy utility. The cleanest approach is
Hibernate.unproxy(entity), which returns the underlying implementation without forcing a database hit if the proxy is uninitialized. Cast the result to your entity type:MyEntity real = (MyEntity) Hibernate.unproxy(proxy);. This is the method to prefer in modern Hibernate versions. - Alternatively, initialize then unwrap. If you need the field values loaded, call
Hibernate.initialize(proxy)first. This triggers a SELECT against the database. After initialization,Hibernate.unproxy(proxy)still returns the target instance, and you can copy its fields into a new detached object if you need one that survives session closure. - Copy state into a fresh instance when crossing session boundaries. If the goal is a detached object you can serialize or send to a client, create
MyEntity copy = new MyEntity();and copy each mapped field, or use a mapper such as MapStruct, ModelMapper, or a manual copy constructor. Do not just cast the proxy and store it, because lazy fields will throwLazyInitializationExceptiononce the session closes. - Verify the result. Check that
copy.getClass()equalsMyEntity.class, thatHibernate.isInitialized(copy)returnstrue, and that all fields you need are populated. If you are returning the object from a service method, log the class name once during development to catch any proxy that slipped through. - Handle collections separately. Persistent collections such as
PersistentSetorPersistentBagare also proxies. Unwrapping the parent entity does not unwrap its collections. Initialize them withHibernate.initialize(entity.getChildren())or copy them into plainArrayListandHashSetinstances.
Common Mistakes
Casting a proxy directly to the entity class looks like it works, because the proxy is a subclass. The problem appears later: getClass() returns the generated subclass, Jackson may serialize extra fields, and equals() implementations that compare classes will fail. Always unwrap rather than cast.
Another frequent error is calling Hibernate.unproxy on a detached object. If the session is closed and the proxy was never initialized, the call may return the proxy itself or throw an exception depending on version. Initialize before detaching, or reattach the entity to a new session first.
Developers also forget that session.get() returns a real instance while session.load() returns a proxy. Choosing the wrong method at load time is often the root cause of the whole problem, so review the fetch strategy before writing unwrap code.
A final trap is assuming that unwrapping also detaches the object. It does not. The returned instance is still managed by the session, and changes to it will be flushed on transaction commit. If you need a read-only snapshot, copy the fields explicitly.
Tips
Prefer Hibernate.unproxy() over the older ProxyUnwrapper or reflection-based tricks, because it is supported and version-stable. If you are on Spring, Hibernate.unproxy works identically through the Session obtained from the EntityManager.
Design your mappings to avoid the problem in the first place: use DTO projections for read paths, fetch joins for data you know you will need, and @ManyToOne(fetch = FetchType.LAZY) only where laziness is genuinely useful. Every unwrap is a sign that the fetch plan and the use case disagree.
When serializing to JSON, configure your mapper to ignore Hibernate metadata fields such as hibernateLazyInitializer and handler, or use DTOs. This is often simpler than unwrapping every proxy in a graph.
Write a small utility method that takes an Object, checks Hibernate.isInitialized, unwraps, and returns the result, so the logic lives in one place rather than being scattered across services.
Troubleshooting
If Hibernate.unproxy returns the same proxy, the object was likely detached or the session was closed. Reattach the entity with session.update() or session.merge() before unwrapping, or load it fresh by identifier.
If you get a LazyInitializationException after unwrapping, a lazy association was accessed outside the session. Initialize the specific association inside the transaction, or switch to a fetch join that loads it eagerly for that query.
If ClassCastException appears, the proxy represents a different subclass than you assumed, often because of inheritance mapping. Inspect Hibernate.getClass(proxy) to see the real mapped type before casting.
If the unwrapped object still has null fields, the proxy was uninitialized and you never triggered a load. Call Hibernate.initialize() inside an open session first.
Frequently Asked Questions
Does unwrapping a proxy hit the database?
No. Hibernate.unproxy() only returns the underlying target instance. A database query happens only when you initialize the proxy or access a lazy field.
Can I unwrap a proxy after the session is closed?
Not reliably. Once detached, the proxy cannot load its state, so initialize and copy the data while the session is still open.
Is a Hibernate proxy the same as a lazy-loaded entity?
They are related but not identical. A proxy is a placeholder subclass; lazy loading is the strategy that creates it. An entity can be lazily loaded without being a proxy if the fetch plan loads it eagerly.
Why does getClass() return a strange name?
Because the proxy is a generated subclass. Use Hibernate.getClass(entity) or unwrap first to get the real mapped type.
Do I need to unwrap collections too?
Yes. Persistent collections are separate proxies. Initialize or copy them independently of the parent entity.
Can I avoid proxies entirely?
You can reduce them by using DTO projections, eager fetch joins for known use cases, and session.get() instead of session.load(). Some proxies will still appear in large object graphs.