Hibernate and You



Getting started

Let me be blunt, hibernate is a pain. It is cranky, tempermental, and at times cryptic. But even with those flaws it is one heck of a great product. Hibernate abstracts all of your persistent storage and allows you to learn one "language" (HQL - Hibernate Query Language) to save, retrieve, and load your data. This means, once learned, you can concentrate your efforts on your business logic instead of your persistence framework.

First things first, the best way to acclimate yourself to hibernate is....tada...go to the hibernate webiste. Specifically, read through the hibernate quickstart and tutorial.

Once you have read the quick start (don't sweat that the test doesn't completely work on porsche or strauss) and tutorial, you have the basic structural knowledge to work with hibernate. The reading in BFLJ, is also useful if you want a different view of how hibernate works. I did not find it as useful since their examples required a large amount of change to make them work. The saving grace of the BFLJ book is that it does show you how to properly set-up a "List" of items. This is the biggest stumbling block and the most difficult thing to master in hibernate.


Next steps

The easiest part of Hibernate, though also the easiest part to mess up, is the configuration file. I used the hbm.xml file as I prefer the structure that XML provides, it makes finding things really easy. Hibernate supports multiple other initialization files, including hibernate.properties and nested code. Use what feels right. The tricky part to the configuration files (for hibernate and each of your classes) is that they have to follow your class files. This was a steep learning curve for us as the errors were pretty cryptic. If you receive an initialization error or NoClassDefError, you most likely have misplaced XMLs.

Build jUnit tests

Build jUnit tests

Build jUnit tests

I repeated that three times because it is the most important thing you can do. First, because you can use it to "bootstrap" data into your db for testing. Second because test driven development creates good code. Period, end of story.

Finally, make sure to build CRUD (CReate,Update,Delete) functions for all of your objects in some *Manager.java. I prefer to use one class, I have seen many people who make a Manager per object, again pros and cons to both.

Build a HibernateUtil class (feel free to use ours) as a singleton. This is just good practice as you will not create more references in memory than you need.




Permissions and Authors

This code is useable for commercial, academic, or personal use. The authors, as listed below, hold no responsibility to any harm, loss, or damages caused by using our code.

Authors