manning Hibernate in Action phần 1 - Pdf 20

Hibernate in Action
Hibernate in Action
CHRISTIAN BAUER
GAVIN KING
MANNING
Greenwich
(74° w. long.)
Licensed to Jose Carlos Romero Figueroa <[email protected]>
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in
quantity. For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue Fax: (203) 661-9018
Greenwich, CT 06830 email: [email protected]
©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, without
prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books they publish printed on acid-free paper, and we exert our best efforts to that end.
.
Manning Publications Co. Copyeditor: Tiffany Taylor
209 Bruce Park Avenue Typesetter: Dottie Marsico
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1932394-15-X
Printed in the United States of America

The cost of the
mismatch 15
1.3 Persistence layers and alternatives 16
Layered architecture 17

Hand-coding a persistence layer with
SQL/JDBC 18

Using serialization 19

Considering EJB
entity beans 20

Object-oriented database systems 21
Other options 22
1.4 Object/relational mapping 22
What is ORM? 23

Generic ORM problems 25
Why ORM? 26
1.5 Summary 29
v
Licensed to Jose Carlos Romero Figueroa <[email protected]>
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



Transparent and
automated persistence 65

Writing POJOs 67
Implementing POJO associations 69

Adding logic to
accessor methods 73
3.3 Defining the mapping metadata 75
Metadata in XML 75

Basic property and class
mappings 78

Attribute-oriented programming 84
Manipulating metadata at runtime 86
3.4 Understanding object identity 87
Identity versus equality 87

Database identity with
Hibernate 88

Choosing primary keys 90
3.5 Fine-grained object models 92
Entity and value types 93

Using components 93
3.6 Mapping class inheritance 97
Table per concrete class 97

Outside the
identity scope 121

Implementing equals() and hashCode() 122
4.2 The persistence manager 126
Making an object persistent 126

Updating the persistent state
of a detached instance 127

Retrieving a persistent object 129
Updating a persistent object 129

Making a persistent object
transient 129

Making a detached object transient 130
4.3 Using transitive persistence in Hibernate 131
Persistence by reachability 131

Cascading persistence with
Hibernate 133

Managing auction categories 134
Distinguishing between transient and detached instances 138
4.4 Retrieving objects 139
Retrieving objects by identifier 140

Introducing HQL 141
Query by criteria 142

Using managed versioning 169

Granularity of a
Session 172

Other ways to implement optimistic locking 174
Licensed to Jose Carlos Romero Figueroa <[email protected]>
viii CONTENTS
5.4 Caching theory and practice 175
Caching strategies and scopes 176

The Hibernate cache
architecture 179

Caching in practice 185
5.5 Summary 194
6
Advanced mapping concepts 195
6.1 Understanding the Hibernate type system 196
Built-in mapping types 198

Using mapping types 200
6.2 Mapping collections of value types 211
Sets, bags, lists, and maps 211
6.3 Mapping entity associations 220
One-to-one associations 220

Many-to-many associations 225
6.4 Mapping polymorphic associations 234
Polymorphic many-to-one associations 234

results
257
7.3 Joining associations 258
Hibernate join options 259

Fetching associations 260
265
268
Using aliases with joins 262

Using implicit joins
Theta-style joins 267

Comparing identifiers
7.4 Writing report queries 269
Projection 270

Using aggregation 272

Grouping 273
Restricting groups with having 274

Improving performance
with report queries
275
Licensed to Jose Carlos Romero Figueroa <[email protected]>
ix CONTENTS
7.5 Advanced query techniques 276
Dynamic queries 276


9
Using the toolset 348
9.1 Development processes 349
Top down 350

Bottom up 350

Middle out (metadata
oriented) 350

Meet in the middle 350
Roundtripping 351
9.2 Automatic schema generation 351
Preparing the mapping metadata 352

Creating the
schema 355

Updating the schema 357
9.3 Generating POJO code 358
Adding meta-attributes 358

Generating finders 360
Configuring hbm2java 362

Running hbm2java 363
9.4 Existing schemas and Middlegen 364
Starting Middlegen 364

Restricting tables and

foreword
Relational databases are indisputably at the core of the modern enterprise.
While modern programming languages, including Java
TM
, provide an intuitive,
object-oriented view of application-level business entities, the enterprise data
underlying these entities is heavily relational in nature. Further, the main strength
of the relational model—over earlier navigational models as well as over later
OODB models—is that by design it is intrinsically agnostic to the programmatic
manipulation and application-level view of the data that it serves up.
Many attempts have been made to bridge relational and object-oriented tech-
nologies, or to replace one with the other, but the gap between the two is one of
the hard facts of enterprise computing today. It is this challenge—to provide a
bridge between relational data and Java
TM
objects—that Hibernate takes on
through its object/relational mapping (
ORM) approach. Hibernate meets this
challenge in a very pragmatic, direct, and realistic way.
As Christian Bauer and Gavin King demonstrate in this book, the effective use
of
ORM technology in all but the simplest of enterprise environments requires
understanding and configuring how the mediation between relational data and
objects is performed. This demands that the developer be aware and knowledge-
able both of the application and its data requirements, and of the
SQL query lan-
guage, relational storage structures, and the potential for optimization that
relational technology offers.
Not only does Hibernate provide a full-function solution that meets these
requirements head on, it is also a flexible and configurable architecture. Hiber-

This kind of application creates, manages, and stores structured information and
shares this information between many users in multiple physical locations.
The storage of
EIS data involves massive usage of SQL-based database manage-
ment systems. Every company we’ve met during our careers uses at least one
SQL
database; most are completely dependent on relational database technology at
the core of their business.
In the past five years, broad adoption of the Java programming language has
brought about the ascendancy of the object-oriented paradigm for software devel-
opment. Developers are now sold on the benefits of object orientation. However,
the vast majority of businesses are also tied to long-term investments in expensive
relational database systems. Not only are particular vendor products entrenched,
but existing legacy data must be made available to (and via) the shiny new object-
oriented web applications.
However, the tabular representation of data in a relational system is fundamen-
tally different than the networks of objects used in object-oriented Java applica-
tions. This difference has led to the so-called object/relational paradigm mismatch.
Traditionally, the importance and cost of this mismatch have been underesti-
mated, and tools for solving the mismatch have been insufficient. Meanwhile, Java
developers blame relational technology for the mismatch; data professionals
blame object technology.
xiii
Licensed to Jose Carlos Romero Figueroa <[email protected]>
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

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.
Licensed to Jose Carlos Romero Figueroa <[email protected]>
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
Licensed to Jose Carlos Romero Figueroa <[email protected]>
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

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-
cient 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) 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 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.

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.
Licensed to Jose Carlos Romero Figueroa <[email protected]>
xixABOUT THIS BOOK
Code annotations accompany many of the source code listings, highlighting
important concepts. In some cases, numbered bullets link to explanations that fol-
low the listing.
Hibernate is an open source project released under the Lesser GNU Public
License. Directions for downloading Hibernate, in source or binary form, are
available from the Hibernate web site: www.hibernate.org/.
The source code for all CaveatEmptor examples in this book is available from
http://caveatemptor.hibernate.org/. The CaveatEmptor example application
code is available on this web site in different flavors: for example, for servlet and for
EJB deployment, with or without a presentation layer. However, only the standal-
one persistence layer source package is the recommended companion to this book.
About the authors

EJB specification was available; hence we don’t
discuss it in this book. However, after reading Hibernate in Action, you’ll know all the
fundamentals that will let you quickly understand entity beans in
EJB 3.
For more up-to-date information, see the Hibernate road map: www.hiber-
nate.org/About/RoadMap.
xx
Licensed to Jose Carlos Romero Figueroa <[email protected]>
author online
Purchase of Hibernate in Action includes free access to a private web forum where
you can make comments about the book, ask technical questions, and receive help
from the author and from other users. To access the forum and subscribe to it,
point your web browser to www.manning.com/bauer. This page provides informa-
tion on how to get on the forum once you are registered, what kind of help is avail-
able, and the rules of conduct on the forum. It also provides links to the source
code for the examples in the book, errata, and other downloads.
Manning’s commitment to our readers is to provide a venue where a mean-
ingful dialog between individual readers and between readers and the authors
can take place. It is not a commitment to any specific amount of participation on
the part of the authors, whose contribution to the AO remains voluntary (and
unpaid). We suggest you try asking the authors some challenging questions lest
their interest stray!
xxi
Licensed to Jose Carlos Romero Figueroa <[email protected]>
about the title and cover
By combining introductions, overviews, and how-to examples, Manning’s In Action
books are designed to help learning and remembering. According to research in
cognitive science, the things people remember are things they discover during
self-motivated exploration.
Although no one at Manning is a cognitive scientist, we are convinced that for

and visual diversity for a more varied personal life. Or a more varied and interest-
ing intellectual and technical life.
We at Manning celebrate the inventiveness, the initiative, and the fun of the
computer business with book covers based on the rich diversity of regional life two
centuries ago brought back to life by the pictures from this travel book.
Licensed to Jose Carlos Romero Figueroa <[email protected]>
Licensed to Jose Carlos Romero Figueroa <[email protected]>
Understanding
object/relational persistence
This chapter covers

Object persistence with SQL databases

The object/relational paradigm mismatch

Persistence layers in object-oriented
applications

Object/relational mapping basics
1
Licensed to Jose Carlos Romero Figueroa <[email protected]>
2 CHAPTER 1
Understanding object/relational persistence
The approach to managing persistent data has been a key design decision in every
software project we’ve worked on. Given that persistent data isn’t a new or unusual
requirement for Java applications, you’d expect to be able to make a simple choice
among similar, well-established persistence solutions. Think of web application
frameworks (Jakarta Struts versus WebWork),
GUI component frameworks (Swing
versus

This book is about Hibernate. We’ll cover basic and advanced features and
describe some recommended ways to develop new applications using Hibernate.
Often, these recommendations won’t be specific to Hibernate—sometimes they
will be our ideas about the best ways to do things when working with persistent
data, explained in the context of Hibernate. Before we can get started with Hiber-
nate, however, you need to understand the core problems of object persistence
and object/relational mapping. This chapter explains why tools like Hibernate
are needed.


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status