Hibernate In Action

2y ago
72 Views
9 Downloads
3.45 MB
430 Pages
Last View : 1d ago
Last Download : 2m ago
Upload by : Esmeralda Toy
Transcription

Hibernate in ActionCHRISTIAN BAUERGAVIN KINGMANNINGGreenwich(74 w. long.)

For online information and ordering of this and other Manning books, please visitwww.manning.com. The publisher offers discounts on this book when ordered inquantity. For more information, please contact:Special Sales DepartmentManning Publications Co.209 Bruce Park AvenueGreenwich, CT 06830Fax: (203) 661-9018email: manning@manning.com 2005 by Manning Publications Co. All rights reserved.No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form or by means electronic, mechanical, photocopying, or otherwise, withoutprior written permission of the publisher.Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in the book, and ManningPublications was aware of a trademark claim, the designations have been printed in initialcaps or all caps.Recognizing the importance of preserving what has been written, it is Manning’s policy to havethe books they publish printed on acid-free paper, and we exert our best efforts to that end.Manning Publications Co.209 Bruce Park AvenueGreenwich, CT 06830Copyeditor: Tiffany TaylorTypesetter: Dottie MarsicoCover designer: Leslie HaimesISBN 1932394-15-XPrinted in the United States of America1 2 3 4 5 6 7 8 9 10 – VHG – 07 06 05 04Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

contentsforeword xipreface xiiiacknowledgments xvabout this book xviabout Hibernate3 and EJB 3 xxauthor online xxiabout the title and cover xxii1Understanding object/relational persistence1.1What is persistence?13Relational databases 3 Understanding SQL 4 Using SQLin Java 5 Persistence in object-oriented applications 5 1.2The paradigm mismatch7The problem of granularity 9 The problem of subtypes 10The problem of identity 11 Problems relating to associationsThe problem of object graph navigation 14 The cost of themismatch 15 1.3Persistence layers and alternatives16Layered architecture 17 Hand-coding a persistence layer withSQL/JDBC 18 Using serialization 19 Considering EJBentity beans 20 Object-oriented database systems 21Other options 22 1.4Object/relational mapping 22What is ORM? 23Why ORM? 261.5Summary Generic ORM problems2529vLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es 13

viCONTENTS2Introducing and integrating Hibernate302.1“Hello World” with Hibernate312.2Understanding the architecture 36The core interfaces 38 Callback interfacesTypes 40 Extension interfaces 41 40 2.3Basic configuration41Creating a SessionFactory 42 Configuration innon-managed environments 45 Configuration inmanaged environments 48 2.4Advanced configuration settings51Using XML-based configuration 51 JNDI-boundSessionFactory 53 Logging 54 Java ManagementExtensions (JMX) 55 2.53Summary 58Mapping persistent classes3.159The CaveatEmptor application60Analyzing the business domain 61The CaveatEmptor domain model 613.2Implementing the domain model 64Addressing leakage of concerns 64 Transparent andautomated persistence 65 Writing POJOs 67Implementing POJO associations 69 Adding logic toaccessor methods 73 3.3Defining the mapping metadata75Metadata in XML 75 Basic property and classmappings 78 Attribute-oriented programming 84Manipulating metadata at runtime 86 3.4Understanding object identity87Identity versus equality 87 Database identity withHibernate 88 Choosing primary keys 90 3.5Fine-grained object modelsEntity and value types3.693 92Using components93Mapping class inheritance 97Table per concrete class 97 Table per class hierarchyTable per subclass 101 Choosing a strategy 104 99 Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

CONTENTS3.7Introducing associations105Managed associations? 106 Multiplicity 106The simplest possible association 107 Making the associationbidirectional 108 A parent/child relationship 111 3.84Summary112Working with persistent objects4.1114The persistence lifecycle 115Transient objects 116 Persistent objects 117 Detachedobjects 118 The scope of object identity 119 Outside theidentity scope 121 Implementing equals() and hashCode() 122 4.2The persistence manager126Making an object persistent 126 Updating the persistent stateof a detached instance 127 Retrieving a persistent object 129Updating a persistent object 129 Making a persistent objecttransient 129 Making a detached object transient 130 4.3Using transitive persistence in Hibernate 131Persistence by reachability 131 Cascading persistence withHibernate 133 Managing auction categories 134Distinguishing between transient and detached instances 138 4.4Retrieving objects139Retrieving objects by identifier 140 Introducing HQL 141Query by criteria 142 Query by example 143 Fetchingstrategies 143 Selecting a fetching strategy in mappings 146Tuning object retrieval 151 4.55Summary152Transactions, concurrency, and caching1545.1Transactions, concurrency, and caching5.2Understanding database transactions154156JDBC and JTA transactions 157 The Hibernate TransactionAPI 158 Flushing the Session 160 Understanding isolationlevels 161 Choosing an isolation level 163 Setting anisolation level 165 Using pessimistic locking 165 5.3Working with application transactions168Using managed versioning 169 Granularity of aSession 172 Other ways to implement optimistic locking Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es 174vii

viiiCONTENTS5.4Caching theory and practice175Caching strategies and scopes 176 The Hibernate cachearchitecture 179 Caching in practice 185 5.56Summary194Advanced mapping concepts6.1195Understanding the Hibernate type system 196Built-in mapping types198Using mapping types 6.2Mapping collections of value types6.3Mapping entity associationsSets, bags, lists, and mapsOne-to-one associations6.4200211211220220 Many-to-many associationsMapping polymorphic associations225234Polymorphic many-to-one associations 234 Polymorphiccollections 236 Polymorphic associations and table-perconcrete-class 237 6.57Summary239Retrieving objects efficiently7.1Executing queries241243The query interfaces 243 Binding parametersUsing named queries 249245 7.2Basic queries for objects250The simplest query 250 Using aliases 251 Polymorphicqueries 251 Restriction 252 Comparison operators 253String matching 255 Logical operators 256 Ordering queryresults 257 7.3Joining associations 258Hibernate join options 259 Fetching associations 260Using aliases with joins 262 Using implicit joins 265Theta-style joins 267 Comparing identifiers 268 7.4Writing report queries269Projection 270 Using aggregationRestricting groups with having 274with report queries 275 272 Grouping 273Improving performance Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

CONTENTS7.5Advanced query techniques276Dynamic queries 276 Collection filters 279Subqueries 281 Native SQL queries 283 7.6Optimizing object retrieval 286Solving the n 1 selects problem 286 Using iterate()queries 289 Caching queries 290 7.78Summary292Writing Hibernate applications8.1294Designing layered applications295Using Hibernate in a servlet engine 296Using Hibernate in an EJB container 3118.2Implementing application transactions320Approving a new auction 321 Doing it the hard way 322Using detached persistent objects 324 Using a long session 325Choosing an approach to application transactions 329 8.38.49Handling special kinds of data330Legacy schemas and composite keys330SummaryUsing the toolset9.1Audit logging340347348Development processes349Top down 350 Bottom up 350oriented) 350 Meet in the middleRoundtripping 351 9.2 Automatic schema generation Middle out (metadata350351Preparing the mapping metadata 352 Creating theschema 355 Updating the schema 357 9.3Generating POJO code358Adding meta-attributes 358Configuring hbm2java 3629.4 Generating finders 360Running hbm2java 363Existing schemas and Middlegen364Starting Middlegen 364 Restricting tables andrelationships 366 Customizing the metadata generationGenerating hbm2java and XDoclet metadata 370 Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es 368ix

xCONTENTS9.5XDoclet372Setting value type attributes 372 Mapping entityassociations 374 Running XDoclet 375 9.6Summary376appendix A: SQL fundamentals378appendix B: ORM implementation strategiesB.1Properties or fields? 383B.2Dirty-checking strategies382384appendix C: Back in the real worldC.1The strange copyC.2The more the better 390C.3We don’t need primary keysC.4Time isn’t linear 391C.5Dynamically unsafeC.6To synchronize or not? 392C.7Really fat clientC.8Resuming Hibernate388389390391393394references 395index 397Licensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

forewordRelational databases are indisputably at the core of the modern enterprise.While modern programming languages, including JavaTM, provide an intuitive,object-oriented view of application-level business entities, the enterprise dataunderlying these entities is heavily relational in nature. Further, the main strengthof the relational model—over earlier navigational models as well as over laterOODB models—is that by design it is intrinsically agnostic to the programmaticmanipulation and application-level view of the data that it serves up.Many attempts have been made to bridge relational and object-oriented technologies, or to replace one with the other, but the gap between the two is one ofthe hard facts of enterprise computing today. It is this challenge—to provide abridge between relational data and JavaTM objects—that Hibernate takes onthrough its object/relational mapping (ORM) approach. Hibernate meets thischallenge in a very pragmatic, direct, and realistic way.As Christian Bauer and Gavin King demonstrate in this book, the effective useof ORM technology in all but the simplest of enterprise environments requiresunderstanding and configuring how the mediation between relational data andobjects is performed. This demands that the developer be aware and knowledgeable both of the application and its data requirements, and of the SQL query language, relational storage structures, and the potential for optimization thatrelational technology offers.Not only does Hibernate provide a full-function solution that meets theserequirements head on, it is also a flexible and configurable architecture. Hibernate’s developers designed it with modularity, pluggability, extensibility, and usercustomization in mind. As a result, in the few years since its initial release,xiLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

xiiFOREWORDHibernate has rapidly become one of the leading ORM technologies for enterprise developers—and deservedly so.This book provides a comprehensive overview of Hibernate. It covers how touse its type mapping capabilities and facilities for modeling associations andinheritance; how to retrieve objects efficiently using the Hibernate query language; how to configure Hibernate for use in both managed and unmanagedenvironments; and how to use its tools. In addition, throughout the book theauthors provide insight into the underlying issues of ORM and into the designchoices behind Hibernate. These insights give the reader a deep understandingof the effective use of ORM as an enterprise technology.Hibernate in Action is the definitive guide to using Hibernate and to object/relational mapping in enterprise computing today.LINDA DEMICHIELLead Architect, Enterprise JavaBeansSun MicrosystemsLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

prefaceJust because it is possible to push twigs along the ground with one’s nose doesnot necessarily mean that that is the best way to collect firewood.—Anthony BerglasToday, many software developers work with Enterprise Information Systems (EIS).This kind of application creates, manages, and stores structured information andshares this information between many users in multiple physical locations.The storage of EIS data involves massive usage of SQL-based database management systems. Every company we’ve met during our careers uses at least one SQLdatabase; most are completely dependent on relational database technology atthe core of their business.In the past five years, broad adoption of the Java programming language hasbrought about the ascendancy of the object-oriented paradigm for software development. Developers are now sold on the benefits of object orientation. However,the vast majority of businesses are also tied to long-term investments in expensiverelational database systems. Not only are particular vendor products entrenched,but existing legacy data must be made available to (and via) the shiny new objectoriented web applications.However, the tabular representation of data in a relational system is fundamentally different than the networks of objects used in object-oriented Java applications. This difference has led to the so-called object/relational paradigm mismatch.Traditionally, the importance and cost of this mismatch have been underestimated, and tools for solving the mismatch have been insufficient. Meanwhile, Javadevelopers blame relational technology for the mismatch; data professionalsblame object technology.xiiiLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

xivPREFACEObject/relational mapping (ORM) is the name given to automated solutions to themismatch problem. For developers weary of tedious data access code, the goodnews is that ORM has come of age. Applications built with ORM middleware can beexpected to be cheaper, more performant, less vendor-specific, and more able tocope 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 thepopular 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 satisfythose requests. The result, Hibernate, is a practical solution, emphasizing developer productivity and technical leadership. Hibernate has been used by tens ofthousands of users and in many thousands of production applications.When the demands on their time became overwhelming, the Hibernate teamconcluded that the future success of the project (and Gavin’s continued sanity)demanded professional developers dedicated full-time to Hibernate. Hibernatejoined jboss.org in late 2003 and now has a commercial aspect; you can purchasecommercial support and training from JBoss Inc. But commercial trainingshouldn’t be the only way to learn about Hibernate.It’s obvious that many, perhaps even most, Java projects benefit from the use ofan ORM solution like Hibernate—although this wasn’t obvious a couple of yearsago! As ORM technology becomes increasingly mainstream, product documentation such as Hibernate’s free user manual is no longer sufficient. We realized thatthe 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 behindHibernate’s design.The book you’re holding was an enormous effort that occupied most of ourspare time for more than a year. It was also the source of many heated disputesand 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

acknowledgmentsWriting (in fact, creating) a book wouldn’t be possible without help. We’d firstlike to thank the Hibernate community for keeping us on our toes; without yourrequests 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, MaxRydahl Andersen, Peter Eisentraut, Matt Raible, and Michael A. Koziarski. Thanksfor your endless hours of reading our half-finished and raw manuscript. We’d liketo thank Emmanuel Bernard for his technical review and Nick Heudecker for hishelp 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 Taylorand Liz Welch found all the many mistakes we made in grammar and style. MaryPiergies organized the production of this book. Many thanks for your hard work.Any others at Manning whom we’ve forgotten: You made it possible.xvLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

about this bookWe introduce the object/relational paradigm mismatch in this book and give youa high-level overview of current solutions for this time-consuming problem. You’lllearn how to use Hibernate as a persistence layer with a richly typed domainobject model in a single, continuing example application. This persistence layerimplementation covers all entity association, class inheritance, and special typemapping strategies.We teach you how to tune the Hibernate object query and transaction systemfor the best performance in highly concurrent multiuser applications. The flexibleHibernate 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 haveto work with an existing SQL database, you’ll also be interested in Hibernate’s legacy database integration features and the Hibernate development toolset.RoadmapChapter 1 defines object persistence. We discuss why a relational database with aSQL interface is the system for persistent data in today’s applications, and whyhand-coded Java persistence layers with JDBC and SQL code are time-consumingand error-prone. After looking at alternative solutions for this problem, we introduce object/relational mapping and talk about the advantages and downsides ofthis approach.Chapter 2 gives an architectural overview of Hibernate and shows you themost important application-programming interfaces. We demonstrate HibernatexviLicensed to Jose Carlos Romero Figueroa jose.romero@galicia.seresco.es

ABOUT THIS BOOKxviiconfiguration in managed (and non-managed) J2EE and J2SE environments afterlooking 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 Hibernatemapping 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 inHibernate. This chapter is focused on loading and storing objects in the most efficient way.Chapter 5 discusses concurrent data access, with database and long-runningapplication transactions. We introduce the concepts of locking and versioning ofdata. We also cover caching in general and the Hibernate caching system, whichare closely related to concurrent data access.Chapter 6 completes your understanding of Hibernate mapping techniqueswith more advanced mapping concepts, such as custom user types, collections ofv

vi CONTENTS 2 Introducing and integrating Hibernate 30 2.1 “Hello World” with Hibernate 31 2.2 Understanding the architecture 36 The core interfaces 38 Callback interfaces 40 Types 40 Extension interfaces 41 2.3 Basic configuration 41 Creating a SessionFactory 42 Configuration in non-managed

Related Documents:

Suspend (S3) or hibernate (S4) can not be executed if CPU0 is detected offline: Because x86 BIOS requires CPU0 to resume from sleep To successfully resume from suspend/hibernate, CPU0 must be online before suspend or hibernate: Suspend or hibernate

Spring Hibernate JSF, Primefaces Intergration (Step by Step) Tool: - IDE: STS 3.3.0.RELEASE (or Eclipse Kepler with Maven and STS plug-in) - Server: Apache Tomcat v7.0 - Database: PostgresQSL 9.1, pgAdmin 1.14.0 Used Technologies: - Spring framework 3.2.3.RELEASE - Hibernate 4.1.0.Final - Myfaces 2.1.12 (

Microsoft name for « suspend to disk » feature Available since Windows 2000. This feature is also implemented in non-MS O.S. (MacOSX, Linux,.) \hiberfil.sys Yes, this is this file! It contains a full dump of the memory How do I hibernate? Start Hibernate Command line: Powercfg /hibernate

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types

Persistence for Idiomatic Java 1 Hibernate Reference Documentation 3.5.6-Final by Gavin King, Christian Bauer, Max Rydahl Andersen, Emmanuel Bernard, and Steve Ebersole and thanks to James Cobb (Graphic Design) and Cheyenne Weaver (Graphic Design)

Hibernate i About the Tutorial Hibernate is a high-performance Object/Relational persistence and query service, which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to

solr-common.jar solr-core.jar lucene-snowball.jar These JARs (available in the Hibernate Search distribution) are a subset of the Solr distribution and contain analyzers. While optional, we recommend adding these JARs to your classpath because it greatly simplifies the use of analyzers. This feature is avail-

To assist you in recording and evaluating your responses on the practice test, a Multiple-Choice Answer Sheet, an Answer Key Worksheet, and an Evaluation Chart by test objective are included for the multiple-choice items. Lastly, there is a Practice Test Score Calculation Worksheet. PURPOSE OF THE PRACTICE TEST. The practice test is designed to provide an additional resource to help you .