jMar"s Blog DevSmash Developer Portal

Wednesday, February 6, 2008

Java, Reflection, Hibernate Proxy Objects, and Confetti

After spending the last 3 days scratching my head and pushing Google to its theoretical limits, I have just experienced the ever-satisfying thrill of success. It was one of those moments where a little hole appears in the clouds and a beam of light illuminates my desk while gold and silver confetti float down from the overhead sprinklers. It really was that good; I nearly made an announcement over the intercom.

So here's the setup: we have a web application running on a Weblogic Portal server and we're using Hibernate and Spring. Due to application growth and an expanding data model, we decided it was time to turn lazy loading on (with respect to Hibernate). Meanwhile I'm working on some form processing logic that (for the sake of this discussion) needed to be a runtime annotation consumer.

The section of code was to determine whether a form had values for all of the "Recommended Fields". The recommended fields were designated via a RecommendedField annotation in the model class. All this method knows is that the particular model object will extend MySuperClass. So it's pretty straight forward. Here's a basic outline of what I had going:

public static boolean isComplete(MySuperClass object) {

 Method[] methods = object.getClass().getMethods();
 for(Method method : methods) {
  RecommendedField rField = method.getAnnotation(RecommendedField.class);
  if( null != rField) {
   // do some logic, then return true or false 
  }
 }
 
 return true;
}

Nothing seems glaringly wrong in the code above, but to my consternation, method.getAnnotation() always returned null. Around this time I came to understand one of the side effects of Hibernate lazy loading. In order to allow lazy access to any relational objects, Hibernate returns a "proxy" object that essentially wraps and mimics the object that you wanted. This way when you call a getter, instead of throwing a NullPointerException, Hibernate can retrieve the result from the database.

Great... so what now? While the proxy object will suffice whenever you need to access a public property or method, it quickly becomes apparent that introspection and reflection present a problem. Since the proxy object is not truly an instance of the class that it is wrapping, metadata (such as annotations) are not there.

In truth, this realization was the key to solving the problem. Understanding that the annotations simply didn't exist on the object that I was inspecting prompted me to explore how to retrieve the non-proxy version of the object. Here is the solution that I ultimately came up with:

public static boolean isComplete(MySuperClass object) {
 /*
  *  The type casting below is necessary in order to read the annotations on the object's methods.
  *  The "MySuperClass" object that is passed into this method is really a Hibernate proxy object 
  *  that wraps the MySuperClass object (due to Hibernate's lazy loading).
  */
 if (object instanceof HibernateProxy) {
  object = (MySuperClass)((HibernateProxy)object).getHibernateLazyInitializer().getImplementation();
 }
  
 Method[] methods = object.getClass().getMethods();
 for(Method method : methods) {
  RecommendedField rField = method.getAnnotation(RecommendedField.class);
  if( null != rField) {
   // do some logic, then return true or false 
  }
 }
 
 return true;
}

*Cue confetti*

You'll notice that the commented addition is rather peculiar. It essentially takes the proxy object that was passed in and casts it as a HibernateProxy object. Calling getImplementation() returns a generic object, which I can then recast as a MySuperClass object (which is what it claimed to be in the first place). Since the object I am working with is now a real and true instance of MySuperClass, I can inspect the methods and their annotations without any problems.

There is a word of warning to throw in about this solution: since I am replacing the proxy object with the real object, my assumption is that it is now detached from the Hibernate session. Attempts at lazy loading on the object would most likely return null or throw a LazyLoadException (I have not tested to verify). In my case I don't need to access any more data, so it's not a problem. If your circumstances are different, you can simply create a new instantiation out of the casted object, or attempt to reattach the object to the Hibernate session when you're done.



69 comments:

Anonymous said...

hi. i read that in Hibernate, sometimes you have to fight the framework (i.e. it is one of its shortcomings). we are using jdbc currently and seems to work for us.

Anonymous said...

Thanks for the tip. It works great!!!

Eric said...

Thanks for the informative content. Saved me a lot of time, as I was attempting to architect a solution to convert Hibernate proxies to JAX-WS/JAXB objects via CXF. Works like a champ!

Jeremy Martin said...

@Eric
I have to admit, I wouldn't have thought of that particular solution, but I'm glad this was able to save you some time. I don't look back with too much fondness over that particular issue!

Anonymous said...

nice work!
I was looking for the part to identify hibernate proxies.

Anonymous said...

Thanks so much for the tip. I am working on a client/server disconnected model and this was what I was looking for. Saved me hours.

Anonymous said...

regarding to that article
for all the beginners in Hibernate ,

here you can find a nice video with step by step tutorial how to set up the environment In Hibernate

http://hibernatetutorial.com/Hibernate-tutorial-how-to-set-up-basic-Hibernate-development-environment.html

Alexander en Ilona said...

y tnx im using it too

Ali B said...

Thanks buddy :-) you're a legend!

Anonymous said...

Thank you so much!!! This is exactly what I was looking for!

Luiz said...

Thanks dude! This fits like a glove! Greetings from Brazil.

Anonymous said...

can i get the real object from proxy object without using hibernateproxy class?

Anonymous said...

Great help, thanks to you I can now evict a (now fully initialised) proxy object before entering into a nested conversation within seam, meaning no double nested parent flushing! Woo!

Anonymous said...

Thanks a lot, you saved me from having to pull out the rest of my hair!

Catalina G. Obrien said...

Thanks for your great post. I like your post very much. Thanks...

photo masking

electronic signatures said...

This will be helpful to everyone who will use it, including me. Keep doing what you are doing ! Thanks for sharing with us your web-site.

lionelmessi10 said...

kemaluan keluar cairan nanahmengapa cairan nanah keluar dari kemaluan mengapa cairan nanah keluar dari kemaluan mengapa kemaluan keluar nanah mengapa kemaluan keluar nanah ujung kemaluan keluar nanah ujung kemaluan keluar nanah obat kemaluan keluar nanah obat kemaluan keluar nanah obat penis keluar cairan nanah mengobati kemaluan keluar nanah pada pria mengobati kemaluan keluar nanah pada pria mengobati kemaluan keluar cairan nanah pada pria mengobati kemaluan keluar cairan nanah pada pria mengobati kelamin keluar nanah mengobati kelamin keluar nanah mengobati kemaluan pria yang keluar nanah nanah keluar dari kemaluan nanah keluar dari kemaluan kencing perih dan keluar cairan nanah cairan nanah keluar dari kemaluan cairan nanah keluar dari kemaluan obat ujung kemaluan keluar cairan nanah obat ujung kemaluan keluar cairan nanah

ahmad najib said...

kemaluan keluar cairan nanahmengapa cairan nanah keluar dari kemaluan mengapa cairan nanah keluar dari kemaluan mengapa kemaluan keluar nanah mengapa kemaluan keluar nanah ujung kemaluan keluar nanah ujung kemaluan keluar nanah obat kemaluan keluar nanah obat kemaluan keluar nanah obat penis keluar cairan nanah mengobati kemaluan keluar nanah pada pria mengobati kemaluan keluar nanah pada pria mengobati kemaluan keluar cairan nanah pada pria mengobati kemaluan keluar cairan nanah pada pria mengobati kelamin keluar nanah mengobati kelamin keluar nanah mengobati kemaluan pria yang keluar nanah nanah keluar dari kemaluan nanah keluar dari kemaluan kencing perih dan keluar cairan nanah cairan nanah keluar dari kemaluan cairan nanah keluar dari kemaluan obat ujung kemaluan keluar cairan nanah obat ujung kemaluan keluar cairan nanah

genius786 said...

Many people are addicted to play cool math games on the internet. I am not sure these online games are harmful or useful but if you want to learn math these games could be helping. In this regard our site can help you to play these games free. You can also try here and also find more by going here.

abcya said...

Great article. Thanks for sharing.

youtube to mp3
weather
usps tracking

aliya seen said...

The typing services online provides best tricks to make assignment and projects so all the best.

Netflix said...

This is a really super post. Must admit that you are amid the best writer I have read. I appreciate your making the effort to discuss this class of article.

facebook video downloader
Netflix

Bilal Bilal said...

Skrotpræmie this is a super post.skrotbil , skrotpræmie http://skrotpriser.com

Love KidsTV said...

Thanks for your post. Click to play Plants vs Zombies , Solitaire,Tom And Jerry Games, Brain Games, Happy Wheels , FNAF , Five Nights At Freddy's

happy wheels said...

Hi there, You’ve done a great job. I will definitely digg it and personally suggest to my friends. I am sure they’ll be benefited from this website….

8 ball pool said...

Good blog, I truly love how it is simple on my eyes and the data are well written.

cool math games said...

I'm wondering how I could be notified when a new post has been made.

fighting games said...

I have subscribed to your feed which must do the trick Have a great day.

Mary Green said...

The best resume writing services reviews can reveal the nuances of every top company that specialize on writing your resumes. That is very comfortable for those who haven't found the best one for himself yet.

breetlee said...

Finally I have found something which helped me. Appreciate it! Skrotpræmie

MRc Co said...

Skal du skrotte din bil og samtidig have en høj skrotpræmie , så kontakt os allerede idag. Din skrotbil kan enten indleveres i Valby eller vi kan også afhente din skrotbil på stort set hele København og Sjælland. Er du i tvivl om hvordan det foregår når du skal skrotte din bil, er du meget velkommen til at kontakte os. Vi har mange års erfaring med skrotbiler og vurderer fra gang til gang hvad din skrotbil er værd. Hvis din skrotbil stadivæk kan køre og er i nogenlunde stand, kan du enten sælge din skrotbil til os eller få repareret den og samtidig få et tilbud på at få din bil nysynet.

Trần Linh said...

Nice post. I was convinced by your arguments. Surely you must have extensive knowledge and understanding very much. I admire you, write more. facebook descargar , baixar whatsapp gratis , baixar whatsapp

Emily Trần said...

This time I feel stressed, I go online to find the article to read. I happened to read your article, it's nice and emotional. I love it. baixar facebook , baixar facebook , baixar whatsapp gratis

mrfyzv said...

Maintain the nice perform, My partner and i examine handful of content with this internet site and also I do believe your net website will be genuine intriguing and contains received sectors regarding great details.
http://downloadmyfileshere.com

HAPPY BIRTHDAY said...

Great post! I am actually getting ready to go across, this post is very informative.Get Happy father's Day 2016
fathers Day 2016
father's Day 2016

Anonymous said...

I just want to say : why you do not click to play!

- Mortal Kombat XL
- Atari Breakout
- Dragon Ball Z Games

hoa pikey said...

I enjoyed over read your blog post. Your blog have nice information,
I got good ideas from this amazing blog.
I am always searching like this type blog post. I hope I will see again..
Signature:
soi cau mien bac | soi cau lo chinh xac 100 | soi cau mb | soi cau |

Candy Sim said...

All the best blogs that is very useful for keeping me share the ideas
of the future as well this is really what I was looking for, and I am
very happy to come here. Thank you very much
earn to die
earn to die 2
earn to die 3
Hi! I’ve been reading your blog for a while now and finally got the
earn to die 4
courage to go ahead and give youu a shout out from
earn to die 6
Austin Texas! Just wanted to tell
earn to die 5
you keep up the fantastic work!my weblog
age of war
Hi! I’ve been reading your blog for a while now and finally got the
happy wheels
strike force heroes
slither io
slitherio

Greenwood Jonny said...

This article contains information that is very useful for all readers, Thank you
obat gonore herbal
obat khusus untuk kutil di kemaluan
obat herbal untuk penyakit sipilis raja singa
nama obat untuk penyakit raja singa
cara mengobati penyakit kelamin raja singa
harga obat herbal untuk kutil di sekitar kemaluan
obat untuk penyakit kelamin gonore sipilis raja singa
obat kutil di kemaluan yang alami
pengobatan herbal untuk kutil di kelamin

tyler durden said...

Thanks....hopefully this article can be useful for the visitors.
obat kencing nanah yang cepat sembuh
obat herbal untuk penyakit sipilis

obat kutil kelamin yang alami said...

Thank You dear....hopefully this article can be useful for the visitors.
obat penyakit raja singa dari bahan alami
obat wasir herbal

Regina Hilary said...


The war between humans, orcs and elves continues. Lead your race through a series of epic battles, using your crossbow to fend off foes and sending out units to destroy castles. Researching and upgrading wisely will be crucial to your success!
age of war 3 | slitherio | unfair mario 2 |
The game controls are shown just under . Movement mechanisms primarily include acceleration and tilting controls.
cubefield | tank trouble | happy wheels | earn to die 1 | earn to die 2

obat kutil kelamin yang alami said...

jual obat herbal untuk kencing nanah
obat herbal untuk wasir
cara mencegah wasir
bahaya kutil kelamin
cara menghilangkan kutil
obat kanker dari bahan herbal alami
obat untuk gejala wasir
obat kanker paru paru
obat kutil kelamin yang aman tanpa efek samping
obat kutil kelamin tanpa operasi
obat herbal untuk kutil kelamin
obat manjur untuk kutil kelamin
obat bintik bintik di area telur penis
tanda tanda wanita berpenyakit kelamin
apakah obat callusol manjur untuk mengobati kutil kelamin?
obat herbal untuk kutil kelamin
callusol apa bisa untuk kutil kelamin?
obat kutil kelamin di surabaya

obat kutil kelamin yang alami said...

semoga bermanfaat,,,
mengobati kutil kelamin dengan obat herbal
mengobati iritasi pada kelamin

BiggBoss8 Winner said...

Fathers Daughter images
Sultan Public response
MS Dhoni Box office Collection
Happy Independence Day India
Check AIPMT Result
Send Rakhi Online
Eid Quotes
Bigg Boss Season 10 Live Updates
friendship day Photos
Winner of Bigg Boss 10
Funny Teachers Day Quotes

Cool n Hot said...

happy friendship day images, quotes, wallpapers, wishes, greetings everything is available here

Happy Friendship Day Quotes
Happy Friendship Day Messages
Happy Friendship Day wishes
Happy Friendship Day images
Happy Friendship Day

Narasiman Ramachandran said...

I’m glad I have come across your site it seems very helpful indeed.
Skrotpræmie

Herbal de nature said...

tanaman herbal untuk kutil kelamin
jual obat kutil kelamin herbal
obat kutil kelamin yang manjur dan aman
tanaman herbal untuk sakit wasir
obat kutil kelamin dari bahan herbal yang manjur
cara mengobati kutil di penis

Vikash kumar said...

Happy Teachers Day Images
Ganesh Chaturthi Wishes In Marathi
Ganesh Chaturthi 2016
Ganesh Chaturthi Images
Ganesh Chaturthi Messages
Happy Teachers Day Photos
teachers day messages for thank you
Happy Teachers Day Quotes
Teachers Day Greetings



Herbal de nature said...

There are some interesting points in time in this article but I don’t know if I see all of them center to heart. There is some validity but I will take hold opinion until I look into it further. Good article , thanks and we want more! Added to FeedBurner as well
obat penyakit kulit raja singa
daun kenanga obat raja singa
obat penyakit raja singa pada laki-laki
obat raja singa manjur
obat raja singa murah
obat raja singa paling manjur
obat medis raja singa
obat mujarab raja singa
obat menyembuhkan raja singa
obat mengatasi raja singa
merek obat raja singa
merk obat raja singa
obat untuk mengobati raja singa
obat tradisional mengobati raja singa
cara membuat obat raja singa

OBAT HERBAL UNTUK BINTIK BINTIK DI KEMALUAN said...

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment’s pleasure, for the rest of their lives.
jual obat gonore/kencing nanah
cara mengobati sipilis dengan obat alami
cara cepat menghilangkan kutil
jual obat raja singa

Charlers John said...

I think your blog is very powerful to me. We have hope that u can keep up the good job.
Skrotpræmie

Hold said...

Thanks for your great post. I like your post very much. Thanks...
123movies.biz

Arjuna Subagyo said...

This article is unique and interesting. thanks for your share. I have been meaning to write something like this on my website and you have given me an idea.
obat herbal manjur untuk penyakit wasir atau ambeien
cara mempersempit vagina setalah melahirkan
obat herpes herbal

obat herbal kutil kelamin said...

The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.
tanaman herbal untuk kutil kelamin
jual obat kutil kelamin herbal
obat kutil kelamin yang manjur dan aman
tanaman herbal untuk sakit wasir
obat kutil kelamin dari bahan herbal yang manjur
cara mengobati kutil di penis

show box said...

Thanks for the tip. It works great!!! really thank u
showbox

Pradeep Sharma said...

veterans day 2016 Images
Happy Diwali Images
Dussehra 2016 Images

Unknown said...

I’m impressed, I must say. Really rarely do I encounter a blog that’s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is outstanding; the issue is something that not enough people are speaking intelligently about. I am very happy that I stumbled across this in my search for something relating to this.
konsultasi dokter kelamin online
obat herbal untuk gonore
bagaimana cara mengobati kencing keluar cairan seperti nanah
cara cepat mengobati kutil kelamin

Anonymous said...

christmas 2016 wishes messages
merry christmas wishes in english
christmas 2016 wishes quotes
christmas 2016 wishes for cards

diwali wishes in tamil
diwali wishes in sanskrit
diwali wishes in sanskrit language
diwali wishes for friends

Anonymous said...

ctet result name wise
ctet.nic.in result 2016
ctet merit list

happy diwali wishes advance
Diwali Pics
halloween love quotes
Blank December 2016 Calendar

Unknown said...

This article is unique and interesting. thanks for your share. I have been meaning to write something like this on my website and you have given me an idea.
mengobati kutil kelamin tanpa operasi
obat alternatif untuk penyakit kutil kelamin
obat kutil kelamin yang sudah terbukti manjur
obat herbal untuk kanker

Herbal de nature said...

terima kasih ,, artikelnya bagus,,, semoga bisa menginspirasi untuk kita semua, amin....
jual obat kutil kelamin herbal
obat kutil kelamin yang manjur dan aman
tanaman herbal untuk sakit wasir
obat kutil kelamin dari bahan herbal yang manjur
cara mengobati kutil di penis

gun mayhem said...

This is the game so players feel very fierce , adventurous . You try to join and play this game , you will feel great like.
| tank trouble | learn to fly
gun mayhem | can your pet
| happ wheels

Anonymous said...

Merry Christmas Cards
Christmas Messages for Family
Merry Christmas HD Images
Christmas Quotes for Friends

merry christmas greetings message
merry christmas message greetings
merry Christmas to everyone quotes
merry Christmas greetings message

Anonymous said...

Happy New Year Images
Happy New Year pictures
Happy New year 2017 Pics
best wishes for a happy new year

Anonymous said...

Inspirational Quotes
Inspirational Sayings
daily motivational quotes

happy new year 2017 messages
merry christmas messages
merry christmas 2016 wishes

Anonymous said...

Birthday Messages For Friends
Happy birthday wishes for sister
Birthday Greetings For Friends

happy birthday wishes to brother
funny birthday wishes
happy birthday sms for friends
happy birthday quotes for friends
birthday funny memes

Anonymous said...

Motivational Whatsapp Status in Tamil
Whatsapp Messages in Hindi
Love Status for Whatsapp
Short funny status for whatsapp

Unknown said...

artikel bermutu dan bermanfaat sekali, tetap posting, lanjutkan....
jual obat kencing nanah di jakarta
jual obat herbal untuk penyakit kanker payudara
jual obat herbal untuk kutil kelamin
cara mengobati kutil kelamin dengan cepat
dimana bisa beli obat untuk penyakit jengger