xiv PREFACE Object/relational mapping (ORM)is the name given to automated solutions to the mismatch problem.For developers weary of tedious data access code,the good news is that ORM has come of age.Applications built with ORM middleware can be expected to be cheaper,more performant,less vendor-specific,and more able to cope with changes to the internal object or underlying SQL schema.The astonish- ing thing is that these benefits are now available to Java developers for free. Gavin King began developing Hibernate in late 2001 when he found that the popular persistence solution at the time-CMP Entity Beans-didn't scale to non- trivial applications with complex data models.Hibernate began life as an inde pendent,noncommercial open source project. The Hibernate team (including the authors)has learned ORM the hard way that is,by listening to user requests and implementing what was needed to satisfy those requests.The result,Hibernate,is a practical solution,emphasizing devel oper productivity and technical leadership.Hibernate has been used by tens of thousands of users and in many thousands of production applications. When the demands on their time became overwhelming.the Hibernate team concluded that the future success of the project(and Gavin's continued sanity) demanded professional developers dedicated full-time to Hibernate.Hibernate joined jboss.org in late 2003 and now has a commercial aspect:you can purchase commercial support and training from JBoss Inc.But commercial training shouldn't be the only way to learn about Hibernate. It's obvious that many,perhaps even most,Java projects benefit from the use of an ORM solution like Hibernate-although this wasn't obvious a couple of years ago!As ORM technology becomes increasingly mainstream,product documenta tion such as Hibernate's free user manual is no longer sufficient.We realized that the Hibernate community and new Hibernate users needed a full-length book. not only to learn about developing software with Hibernate,but also to under- stand and appreciate the object/relational mismatch and the motivations behind Hibernate's design. The book you're holding was an enormous effort that occupied most of our spare time for more than a year.It was also the source of many heated disputes and learning experiences.We hope this book is an excellent guide to Hibernate (or,"the Hibernate bible,"as one of our reviewers put it)and also the first com- prehensive documentation of the object/relational mismatch and ORM in gen- eral.We hope you find it helpful and enjoy working with Hibernate
xiv PREFACE Object/relational mapping (ORM) is the name given to automated solutions to the mismatch problem. For developers weary of tedious data access code, the good news is that ORM has come of age. Applications built with ORM middleware can be expected to be cheaper, more performant, less vendor-specific, and more able to cope with changes to the internal object or underlying SQL schema. The astonishing thing is that these benefits are now available to Java developers for free. Gavin King began developing Hibernate in late 2001 when he found that the popular persistence solution at the time—CMP Entity Beans—didn’t scale to nontrivial applications with complex data models. Hibernate began life as an independent, noncommercial open source project. The Hibernate team (including the authors) has learned ORM the hard way— that is, by listening to user requests and implementing what was needed to satisfy those requests. The result, Hibernate, is a practical solution, emphasizing developer productivity and technical leadership. Hibernate has been used by tens of thousands of users and in many thousands of production applications. When the demands on their time became overwhelming, the Hibernate team concluded that the future success of the project (and Gavin’s continued sanity) demanded professional developers dedicated full-time to Hibernate. Hibernate joined jboss.org in late 2003 and now has a commercial aspect; you can purchase commercial support and training from JBoss Inc. But commercial training shouldn’t be the only way to learn about Hibernate. It’s obvious that many, perhaps even most, Java projects benefit from the use of an ORM solution like Hibernate—although this wasn’t obvious a couple of years ago! As ORM technology becomes increasingly mainstream, product documentation such as Hibernate’s free user manual is no longer sufficient. We realized that the Hibernate community and new Hibernate users needed a full-length book, not only to learn about developing software with Hibernate, but also to understand and appreciate the object/relational mismatch and the motivations behind Hibernate’s design. The book you’re holding was an enormous effort that occupied most of our spare time for more than a year. It was also the source of many heated disputes and learning experiences. We hope this book is an excellent guide to Hibernate (or, “the Hibernate bible,” as one of our reviewers put it) and also the first comprehensive documentation of the object/relational mismatch and ORM in general. We hope you find it helpful and enjoy working with Hibernate. Licensed to Jose Carlos Romero Figueroa <jose.romero@galicia.seresco.es>
acknowledgments Writing (in fact,creating)a book wouldn't be possible without help.We'd first like to thank the Hibernate community for keeping us on our toes:without your requests for the book,we probably would have given up early on. A book is only as good as its reviewers,and we had the best.J.B.Rainsberger. Matt Scarpino,Ara Abrahamian,Mark Eagle,Glen Smith,Patrick Peak,Max Rydahl Andersen,Peter Eisentraut,Matt Raible,and Michael A.Koziarski.Thanks for your endless hours of reading our half-finished and raw manuscript.We'd like to thank Emmanuel Bernard for his technical review and Nick Heudecker for his help with the first chapters. Our team at Manning was invaluable.Clay Andres got this project started, Jackie Carter stayed with us in good and bad times and taught us how to write. Marjan Bace provided the necessary confidence that kept us going.Tiffany Taylor and Liz Welch found all the many mistakes we made in grammar and style.Mary Piergies organized the production of this book.Many thanks for your hard work. Any others at Manning whom we've forgotten:You made it possible
xv acknowledgments Writing (in fact, creating) a book wouldn’t be possible without help. We’d first like to thank the Hibernate community for keeping us on our toes; without your requests for the book, we probably would have given up early on. A book is only as good as its reviewers, and we had the best. J. B. Rainsberger, Matt Scarpino, Ara Abrahamian, Mark Eagle, Glen Smith, Patrick Peak, Max Rydahl Andersen, Peter Eisentraut, Matt Raible, and Michael A. Koziarski. Thanks for your endless hours of reading our half-finished and raw manuscript. We’d like to thank Emmanuel Bernard for his technical review and Nick Heudecker for his help with the first chapters. Our team at Manning was invaluable. Clay Andres got this project started, Jackie Carter stayed with us in good and bad times and taught us how to write. Marjan Bace provided the necessary confidence that kept us going. Tiffany Taylor and Liz Welch found all the many mistakes we made in grammar and style. Mary Piergies organized the production of this book. Many thanks for your hard work. Any others at Manning whom we’ve forgotten: You made it possible. Licensed to Jose Carlos Romero Figueroa <jose.romero@galicia.seresco.es>
about this book We introduce the object/relational paradigm mismatch in this book and give you a high-level overview of current solutions for this time-consuming problem.You'll learn how to use Hibernate as a persistence layer with a richly typed domain object model in a single.continuing example application.This persistence layer implementation covers all entity association,class inheritance,and special type mapping strategies. We teach you how to tune the Hibernate object query and transaction system for the best performance in highly concurrent multiuser applications.The flexible Hibernate dual-layer caching system is also an important topic in this book.We dis- cuss Hibernate integration in different scenarios and also show you typical archi- tectural problems in two-and three-tiered Java database applications.If you have to work with an existing SQL database,you'll also be interested in Hibernate's leg- acy database integration features and the Hibernate development toolset. Roadmap Chapter 1 defines object persistence.We discuss why a relational database with a SQL interface is the system for persistent data in today's applications,and why hand-coded Java persistence layers with JDBC and SQL code are time-consuming and error-prone.After looking at alternative solutions for this problem,we intro- duce object/relational mapping and talk about the advantages and downsides of this approach. Chapter 2 gives an architectural overview of Hibernate and shows you the most important application-programming interfaces.We demonstrate Hibernate xvi
xvi about this book We introduce the object/relational paradigm mismatch in this book and give you a high-level overview of current solutions for this time-consuming problem. You’ll learn how to use Hibernate as a persistence layer with a richly typed domain object model in a single, continuing example application. This persistence layer implementation covers all entity association, class inheritance, and special type mapping strategies. We teach you how to tune the Hibernate object query and transaction system for the best performance in highly concurrent multiuser applications. The flexible Hibernate dual-layer caching system is also an important topic in this book. We discuss Hibernate integration in different scenarios and also show you typical architectural problems in two- and three-tiered Java database applications. If you have to work with an existing SQL database, you’ll also be interested in Hibernate’s legacy database integration features and the Hibernate development toolset. Roadmap Chapter 1 defines object persistence. We discuss why a relational database with a SQL interface is the system for persistent data in today’s applications, and why hand-coded Java persistence layers with JDBC and SQL code are time-consuming and error-prone. After looking at alternative solutions for this problem, we introduce object/relational mapping and talk about the advantages and downsides of this approach. Chapter 2 gives an architectural overview of Hibernate and shows you the most important application-programming interfaces. We demonstrate Hibernate Licensed to Jose Carlos Romero Figueroa <jose.romero@galicia.seresco.es>
ABOUT THIS BOOK configuration in managed(and non-managed)J2EE and J2SE environments after looking at a simple"Hello World"application. Chapter 3 introduces the example application and all kinds of entity and rela- tionship mappings to a database schema,including uni-and bidirectional associa- tions,class inheritance,and composition.You'll learn how to write Hibernate mapping files and how to design persistent classes. Chapter 4 teaches you the Hibernate interfaces for read and save operations: we also show you how transitive persistence(persistence by reachability)works in Hibernate.This chapter is focused on loading and storing objects in the most effi- clent way. Chapter 5 discusses concurrent data access,with database and long-running application transactions.We introduce the concepts of locking and versioning of data.We also cover caching in general and the Hibernate caching system,which are closely related to concurrent data access Chapter 6 completes your understanding of Hibernate mapping techniques with more advanced mapping concepts.such as custom user types.collections of values,and mappings for one-to-one and many-to-many associations.We briefly discuss Hibernate's fully polymorphic behavior as well. Chapter 7 introduces the Hibernate Query Language (HQL)and other object- retrieval methods such as the query by criteria(QBC)APL,which is a typesafe way to express an object query.We show you how to translate complex search dialogs in your application to a query by example(QBE)query.You'll get the full power of Hibernate queries by combining these three features;we also show you how to use direct SQL calls for the special cases and how to best optimize query performance Chapter 8 describes some basic practices of Hibernate application architecture. This includes handling the sessionFactory.the popular ThreadLocal session pat tern,and encapsulation of the persistence layer functionality in data access objects (DAO)and J2EE commands.We show you how to design long-running application transactions and how to use the innovative detached object support in Hibernate. We also talk about audit logging and legacy database schemas. Chapter 9 introduces several different development scenarios and tools that may be used in each case.We show you the common technical pitfalls with each approach and discuss the Hibernate toolset (hbm2ddl.hbm2java)and the inte. gration with popular open source tools such as XDoclet and Middlegen
ABOUT THIS BOOK xvii configuration in managed (and non-managed) J2EE and J2SE environments after looking at a simple “Hello World” application. Chapter 3 introduces the example application and all kinds of entity and relationship mappings to a database schema, including uni- and bidirectional associations, class inheritance, and composition. You’ll learn how to write Hibernate mapping files and how to design persistent classes. Chapter 4 teaches you the Hibernate interfaces for read and save operations; we also show you how transitive persistence (persistence by reachability) works in Hibernate. This chapter is focused on loading and storing objects in the most efficient way. Chapter 5 discusses concurrent data access, with database and long-running application transactions. We introduce the concepts of locking and versioning of data. We also cover caching in general and the Hibernate caching system, which are closely related to concurrent data access. Chapter 6 completes your understanding of Hibernate mapping techniques with more advanced mapping concepts, such as custom user types, collections of values, and mappings for one-to-one and many-to-many associations. We briefly discuss Hibernate’s fully polymorphic behavior as well. Chapter 7 introduces the Hibernate Query Language (HQL) and other objectretrieval methods such as the query by criteria (QBC) API, which is a typesafe way to express an object query. We show you how to translate complex search dialogs in your application to a query by example (QBE) query. You’ll get the full power of Hibernate queries by combining these three features; we also show you how to use direct SQL calls for the special cases and how to best optimize query performance. Chapter 8 describes some basic practices of Hibernate application architecture. This includes handling the SessionFactory, the popular ThreadLocal Session pattern, and encapsulation of the persistence layer functionality in data access objects (DAO) and J2EE commands. We show you how to design long-running application transactions and how to use the innovative detached object support in Hibernate. We also talk about audit logging and legacy database schemas. Chapter 9 introduces several different development scenarios and tools that may be used in each case. We show you the common technical pitfalls with each approach and discuss the Hibernate toolset (hbm2ddl, hbm2java) and the integration with popular open source tools such as XDoclet and Middlegen. Licensed to Jose Carlos Romero Figueroa <jose.romero@galicia.seresco.es>
xi ABOUT THIS BOOK Who should read this book? Readers of this book should have basic knowledge of object-oriented software development and should have used this knowledge in practice.To understand the application examples,you should be familiar with the Java programming lan- guage and the Unified Modeling Language. Our primary target audience consists of Java developers who work with SQL based database systems.We'll show you how to substantially increase your produc tivity by leveraging ORM. If you're a database developer,the book could be part of your introduction to object-oriented software development. If you're a database administrator,you'll be interested in how ORM affects per formance and how you can tune the performance of the SQL database manage ment system and persistence layer to achieve performance targets.Since data access is the bottleneck in most Java applications,this book pays close attention to performance issues.Many DBAs are understandably nervous about entrusting per- formance to tool-generated SQL code;we seek to allay those fears and also to highlight cases where applications should not use tool-managed data access.You may be relieved to discover that we don't claim that ORM is the best solution to every problem. Code conventions and downloads This book provides copious examples,which include all the Hibernate applica tion artifacts:Java code.Hibernate configuration files,and XML mapping meta- data files.Source code in listings or in text is in a fixed-width font like this to separate it from ordinary text.Additionally,Java method names,component parameters,object properties,and XML elements and attributes in text are also presented using fixed-width font. Java,HTML,and XML can all be verbose.In many cases,the original source code (available online)has been reformatted;we've added line breaks and reworked indentation to accommodate the available page space in the book.In rare cases even this was not enough,and listings include line-continuation markers.Addi- tionally,comments in the source code have been removed from the listings
xviii ABOUT THIS BOOK Who should read this book? Readers of this book should have basic knowledge of object-oriented software development and should have used this knowledge in practice. To understand the application examples, you should be familiar with the Java programming language and the Unified Modeling Language. Our primary target audience consists of Java developers who work with SQLbased database systems. We’ll show you how to substantially increase your productivity by leveraging ORM. If you’re a database developer, the book could be part of your introduction to object-oriented software development. If you’re a database administrator, you’ll be interested in how ORM affects performance and how you can tune the performance of the SQL database management system and persistence layer to achieve performance targets. Since data access is the bottleneck in most Java applications, this book pays close attention to performance issues. Many DBAs are understandably nervous about entrusting performance to tool-generated SQL code; we seek to allay those fears and also to highlight cases where applications should not use tool-managed data access. You may be relieved to discover that we don’t claim that ORM is the best solution to every problem. Code conventions and downloads This book provides copious examples, which include all the Hibernate application artifacts: Java code, Hibernate configuration files, and XML mapping metadata files. Source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. Additionally, Java method names, component parameters, object properties, and XML elements and attributes in text are also presented using fixed-width font. Java, HTML, and XML can all be verbose. In many cases, the original source code (available online) has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers. Additionally, comments in the source code have been removed from the listings. Licensed to Jose Carlos Romero Figueroa <jose.romero@galicia.seresco.es>