Hibernate is a lightweight object/relational mapping service for Java. What does that mean? It’s a way to work easily and efficiently with information from a relational database in the form of natural Java objects. But that description doesn’t come close to conveying how useful and exciting the technology is. I’m not the only person who thinks so: Hibernate 2.1 won Software Development magazine’s 14th annual Jolt Award in the “Libraries, Frameworks, and Components” category. (And, with the hindsight afforded by the opportunity to write this updated and expanded version of Hibernate: A Developer’s Notebook, I can say I was truly thrilled that the first edition of this book, which covered Hibernate 2, was itself a Productivity Winner in the 15th annual Awards.)
So, what’s great about Hibernate? All nontrivial applications (and even many trivial ones) need to store and use information, and these days this usually involves a relational database. Worlds apart from Java objects, databases often involve people with different skills and specializations. Bridging these two worlds has been important for a while, but it used to be quite complex and tedious.
Most people start out struggling to write a few SQL queries, embedding these awkwardly as strings within Java code, and working with Java database connectivity (JDBC) to run them and process the results. JDBC has evolved into a rich and flexible database communication library, which now provides ways to simplify and improve upon this approach, but there is still a fair degree of tedium involved. People who work with data a great deal need more power—some way of moving the queries out of the code and making them act more like well-behaved components in an object-oriented world.
Such capabilities had been part of my own (even more) lightweight object/relational layer for years. It began with a Java database connection and query pooling system written by my colleague Eric Knapp for the Lands’ End e-commerce site. Our pooler introduced the idea of external SQL templates that could be accessed by name and efficiently combined with runtime data to generate the actual database queries. Only later did it grow to include the ability to bind these templates directly to Java objects, by adding simple mapping directives to the templates.
Although far less powerful than a system like Hibernate, this approach proved valuable in many projects of different sizes and in widely differing environments. We continued to use it until the first version of this book, most recently in building IP telephony applications for Cisco’s CallManager platform. However, we now use Hibernate for new projects, and once you work through this book, you’ll understand why. You will probably make the same decision yourself. Hibernate does a tremendous amount for you, and does it so easily that you can almost forget you’re working with a database. Your objects are simply there when you need them. This is how technology should work.
You may wonder how Hibernate relates to Enterprise JavaBeans™ (EJBs). Is it a competing solution? When would you use one over the other? In fact, you can use both. Not every application needs the complexity of EJBs; many can simply use Hibernate directly to interact with a database. On the other hand, EJBs are sometimes indispensable for very complex three-tier application environments. In such cases, Hibernate may be used by an EJB Session bean to persist data, or it might be used to persist BMP entity beans.
In fact, even the EJB committee was eventually sold on the power and convenience of Hibernate’s “plain old Java objects” approach to persistence—the Java Persistence Architecture introduced in EJB version 3 (and usable outside of an EJB environment) was heavily influenced by Hibernate. In fact, Hibernate 3 can be used as an implementation of JPA in a fully portable way (although, as you’ll see in Chapter 7, you’ll probably still want to take advantage of Hibernate’s extensions to JPA).
The development of Hibernate has clearly been a watershed event in the interaction between Java and relational databases. The Java world owes Gavin King and his intrepid cohorts a huge debt of thanks for making our lives easier. This book is intended to help you learn how take advantage of their achievement as quickly as possible.
This book started as part of O’Reilly’s Developer’s Notebook™ series, a new approach to helping readers rapidly come up to speed with useful new technologies. Although it has since been expanded to touch on more of the related technologies that Hibernate users might want to explore, it is not intended to be a comprehensive reference manual for Hibernate. Instead, it reflects the authors’ own exploration of the system, from initial download and configuration through a series of projects that demonstrate how to accomplish a variety of practical goals.
By reading and following along with these examples, you’ll be able to get your own Hibernate environment set up quickly and start using it for realistic tasks right away. It’s as if you can “walk with us” through terrain we’ve mapped out, while we point out useful landmarks and tricky pitfalls along the way.
Although we certainly include some background materials and explanations of how Hibernate works and why, this is always in the service of a focused task. Sometimes we’ll refer you to the reference documentation or other online resources if you’d like more depth about one of the underlying concepts or details about a related but different way to use Hibernate.
Once you’re past the first few chapters, you don’t need to read the rest in order; you can jump to topics that are particularly interesting or relevant to you. The examples do build on each other, but you can download the finished source code from the book’s web site (you may want to start with the previous chapter’s files and follow along, making changes yourself to implement the examples you’re reading). You can always jump back to the earlier examples if they turn out to be interesting because of how they relate to what you’ve just learned.
This book follows certain conventions for font usage. Understanding these conventions upfront will make it easier to use this book.
Used for filenames, file extensions, URLs, application names, emphasis, and introduction of new terms.
Used for Java class names, methods, variables, properties, data types, database elements, and snippets of code that appear in text.
Constant width bold
Used for commands you enter at the command line and to highlight new code inserted in a running example.
Constant width italic
Used to annotate output.
The web site for this book, http://www.oreilly.com/catalog/9780596517724/, offers some important materials you’ll want to know about. All the examples for this book can be found there, organized by chapter.
The examples are available as a ZIP archive and a compressed TAR archive.
In many cases, the same files are used throughout a series of chapters, and they evolve to include new features and capabilities from example to example. Each chapter folder in the downloadable archive contains a snapshot of the state of the example system, reflecting all the changes and new content introduced in that chapter.
Please address comments and questions concerning this book to the publisher:
|O’Reilly Media, Inc.|
|1005 Gravenstein Highway North|
|Sebastopol, CA 95472|
|800-998-9938 (in the United States or Canada)|
|707-829-0515 (international or local)|
O’Reilly’s web site for this book, where we list errata, examples, or any additional information, can be accessed at:
To comment or ask technical questions about this book, send email to:
For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at:
We’re intensely grateful to Gavin King, Christian Bauer, Steve Ebersole, Max Andersen, and everyone else who has created and improved Hibernate. Our enthusiasm for how this tool has made our lives better as Java developers is why Jim wrote the Developer’s Notebook in the first place, and why all three of us decided to produce this expanded and updated book. Hopefully it shows!
We’re particularly indebted to our technical reviewers Michael Podrazik, Stefan Winz, and Henri Yandell for their careful, detailed, and helpful suggestions. They each contributed greatly to making this a better book.
We’d also like to thank Keith Fahlgren, Adam Witwer, and the other members of O’Reilly’s production department who put in lots of work helping us come up to speed in the new DocBook XML authoring environment, and getting the book to look as good as it could.
The Stripes example includes code developed by Tim Fennell, under the Apache Software License. The license for Stripes is located at ch14/stripes_license.txt in the examples download.
Any list of thanks has to start with my parents for fostering my interest in computing even when we were living in countries that made that a major challenge, and with my partner Joe for putting up with it today when it has flowered into a major obsession. I’d also like to acknowledge my employer, Berbee, for giving me an opportunity to delve deeply into Java and build skills as an architect of reusable APIs; for letting me stay clear of the proprietary, platform-specific tar pit that is engulfing so much of the programming world; for surrounding me with such incredible colleagues; and for being supportive when I wanted to leverage these experiences in writing this book.
Ryan and Tim jumped in when I wanted some help expanding the second version to cover related technologies that have come up like Spring and Stripes. Their enthusiasm and expertise have been a major factor in getting this long-delayed update in motion.
Marc Loy got me connected with the wonderful folks at O’Reilly by inviting me to help with the second edition of Java Swing, and Mike Loukides has been patiently working with me ever since—encouraging me to write a book of my own. In Hibernate he found the perfect topic to get me started, and it turned out well enough that we came back to expand it. Deb Cameron, our revisions editor for the Swing effort, played a big role in turning my tentative authorial ambitions into a rewarding reality. I’m also grateful she was willing to “loan me out” from helping with the third edition of Learning Emacs to take on the Hibernate project.
I remain grateful to my technical reviewers for the first version of this book, Adrian Kellor and Curt Pederson. They looked at some very early drafts and helped set my tone and direction, as well as reinforcing my enthusiasm about the value of the project. As that book came together, Bruce Tate provided an important sanity check from someone actively using and teaching Hibernate, and offered some great advice and even more encouragement. Eric Knapp reviewed a large portion with an eye toward using the book in an instructional setting at a technical college, and reminded me to keep my feet on the ground. Tim Cartwright jumped in at the end, working with a nearly complete draft in an effort to understand Hibernate as a potential platform for future work, and providing a great deal of useful feedback about the content and presentation.
I’d like to thank Jim for inviting me to help out on this book and for all the coaching he’s given me on the book and in my day job. I’d like to thank Tim for providing technical help and consolation when I needed each. Thanks to Mike Loukides for being patient with me and for helping to provide some direction.
I’d also like to thank my wife, Sarah, for being so helpful, patient, and loving. Things could have turned ugly, and your support was the primary reason that didn’t happen. Finally, I’d like to thank my parents for giving me the tools to get where I am now and wherever I’m going.
Thanks to Jim and Ryan for asking me to contribute to this book with the Spring and Maven chapters. Thanks to Mike Loukides for providing a good environment for writing and collaboration. Keith Fahlgren was an invaluable resource when it came to the logistics of writing. The O’Reilly publishing technology group went out of its way a number of times to help us all with various issues relating to DocBook markup and version control.
Thanks to Stefan Winz, Robert Sorkin, Ahmed Abu-Zayedeh, Bob Hartlaub, Rock Podrazik, and Jeff Leeman; you have all provided the necessary proving grounds and been unwitting guinea pigs for the code presented in both the Spring and Maven chapters. Thanks to my daughter Josephine Ann for providing essential and critical feedback on the Hibernate Annotations chapter; Josephine, you might only be two years old, but you’ve picked up Hibernate very quickly. Thanks for taking time off from watching Blue’s Clues to catch those silly errors in my pom.xml file. Thanks to Susan, my wife, for being perfect.