Tuesday, July 29, 2008

Access the target object from a Hibernate CGLIB proxy

Sometimes in Hibernate when you have Lazy Loaded lists of objects you will end up interacting with a proxied instance of the object rather than the object itself, even if you access members of the object so that you know it's been loaded from the database.

This situation can be tricky because your object walks like a duck and talks like a duck...but it's a proxy. You want the duck! You can do something like the following to lure it out:

if (asset instanceof org.hibernate.proxy.HibernateProxy) {
    BankAccount ss = (BankAccount) ((HibernateProxy)asset).getHibernateLazyInitializer().getImplementation();
    String desc = asset.getDescriptionTxt();


Anonymous said...

After 2 Hours of Searching, I Found this Blog. You did a goog Job sharing the Code. Thanks a lot

Anonymous said...

Thanx a ton!!!!