Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Hibernate proxy to a real entity object

During a Hibernate Session, I am loading some objects and some of them are loaded as proxies due to lazy loading. It's all OK and I don't want to turn lazy loading off.

But later I need to send some of the objects (actually one object) to the GWT client via RPC. And it happens that this concrete object is a proxy. So I need to turn it into a real object. I can't find a method like "materialize" in Hibernate.

How can I turn some of the objects from proxies to reals knowing their class and ID?

At the moment the only solution I see is to evict that object from Hibernate's cache and reload it, but it is really bad for many reasons.

like image 244
Andrey Minogin Avatar asked Feb 07 '10 09:02

Andrey Minogin


People also ask

What is Hibernate proxy object?

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.

Which method returns proxy object in Hibernate?

Explanation: load() method returns proxy object. load() method should be used if it is sure that instance exists.

What is lazy proxy in Hibernate mapping?

Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement (via the excellent CGLIB library). By default, Hibernate3 generates proxies (at startup) for all persistent classes and uses them to enable lazy fetching of many-to-one and one-to-one associations.

What is JPA proxy?

The JPA lazy loading mechanism can either be implemented using Proxies or Bytecode Enhancement so that calls to lazy associations can be intercepted and relationships initialized prior to returning the result back to the caller.


2 Answers

Here's a method I'm using.

public static <T> T initializeAndUnproxy(T entity) {     if (entity == null) {         throw new             NullPointerException("Entity passed for initialization is null");     }      Hibernate.initialize(entity);     if (entity instanceof HibernateProxy) {         entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()                 .getImplementation();     }     return entity; } 
like image 97
Bozho Avatar answered Sep 28 '22 04:09

Bozho


Since Hibernate ORM 5.2.10, you can do it likee this:

Object unproxiedEntity = Hibernate.unproxy(proxy); 

Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext implementation:

Object unproxiedEntity = ((SessionImplementor) session)                          .getPersistenceContext()                          .unproxy(proxy); 
like image 35
Vlad Mihalcea Avatar answered Sep 28 '22 05:09

Vlad Mihalcea