Hibernate, proxies, and programming to interfaces

When working simply with Hibernate, you end up coding to concrete classes. This violates the idea that you should program to a type, not an implementation. It also means that various things you tend to do with Hibernate (like writing getters and setters) end up “polluting” your domain classes.

There is a way to get Hibernate to give you back interfaces instead of concrete classes. It’s called a Hibernate proxy. When Hibernate uses lazy-loading (on by default in HIbernate 3), it gives you back proxies, rather than direct instances of the class. These proxies are dynamically generated subclasses of the nominated “proxy class”. This proxy class, by default, is the actual mapped class, but it does not have to be – it can be an interface, as long as the mapped class implements the interface.

This means that you can put on the various Hibernate hooks that you may need, make them public if you want (e.g. for testing), but not have to worry about your production code getting at them. And the proxy is a real proxy – you would not be able to cast it to the mapped class, as there is no inheritance chain back to it.

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 20 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 22 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s