Tuesday, September 18, 2007

Hibernate Annotations and You Ain't Gonna Need It

In the last post I showed a Hibernate demo. I wrote it to show how to hook Mayfly to Hibernate, but it also was my first experience with Hibernate Annotations. I have long been hoping that Hibernate Annotations would ease the pain of hibernate, specifically by eliminating the need to keep looking back and forth between XML mapping files, Java code, and database schemas.

Basically, my experience to date is quite positive. The key thing to note about the demo is all the things which aren't there.

This starts with configuration. There is no hibernate.cfg.xml file, no database username and password, no JDBC URL and driver (I guess some of those would come back if we were talking to a database like MySQL as opposed to Mayfly, but the hibernate.cfg.xml wouldn't).

Next, and more importantly, look at Foo. Here we just need an instance variable for each database column, an annotation @Entity at the start, and an annotation @Id on the primary key. Since the instance variables are named the same as the columns, we don't need to specify a mapping between the two. There's no XML mapping file. I also don't bother with getters and setters. I can always add them later (that's why refactoring browsers have "encapsulate field"), and using them only where they are providing some value avoids a huge amount of clutter. (Or to put it more provocatively, "You Ain't Gonna Need Getters and Setters").

Just getting everything into Foo.java, rather than splitting it between Foo.java and Foo.hbm.xml, is a huge win. You can't just control-click over to the XML file (in a browser like Eclipse), and even if you could you'd be looking back and forth rather than just having everything in one place as with annotations.

So positive impressions confirmed. Definitely plan to give annotations a try on a larger project next time I have a choice.

1 comment:

Anonymous said...

Hi Jim,

Sorry for leaving this off-topic message here but I couldn't find any other way to contact you; so feel free to remove it. I'm currently editing the Usenet category of dmoz and I'd love to get help from someone who edited this category before. Please feel free to send a message using the feedback form (by clicking on the editor name at the bottom of the page).

Sorry again for this off-topic message.
alt.lost.editor.support.collaborate-with.help