Apress - Pro JPA 2 Mastering the Java Persistence API ... - DAINF

farflungconvyancerΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

408 εμφανίσεις

Keith
Schincariol
JPA 2
Companion
eBook Available
Pro
Java™ EE 6
compliant

this print for content only—size & color not accurate
  CYAN
  MAGENTA
  YELLOW
  BLACK
  PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Pro JPA 2: Mastering the Java


Persistence API
Dear Reader,
It’s hard to believe that over 3 years have gone by since the initial 1.0 release of
the Java™ Persistence API. In that time we have seen it go from fledgling API
to mainstream persistence standard. Along the way, many of you cut your JPA
teeth using the first edition of this book, and we’re happy we were there to help!
JPA 2.0 includes a host of new features, such as additional object-relational
mappings, more object modeling flexibility, typed queries, and a brand-new
criteria API, to name a few. With so much to talk about, we were excited to
update the book and explain all the new features, but we also included some
hints and tips to help you use the API in practice.
If you already have experience with JPA 1.0 then you should benefit from
the version tips that point out when a feature was added in 2.0. These tips
were also designed to help users who are writing to a JPA 1.0 implementation,
and are not yet able to make use of the 2.0 features.
Those of you that are new to JPA can rest assured that you were not for-
gotten. We have remained true to our original intent to take someone from
having no JPA knowledge all the way to being an advanced JPA’er. You should
be able to quickly learn in the first two chapters what you need to know to get
started. (Veteran JPA programmers might want to start at Chapter 3!) Finally,
we want to thank you for making the previous edition of this book such a suc-
cess. We are pleased that it has become the primary resource for JPA develop-
ers, and hope that you will find this edition equally valuable.
Mike Keith, JPA 2.0 Expert Group Member, and Merrick Schincariol
Authors of
Pro EJB™ 3: Java™
Persistence API
US $49.99
Shelve in
Java Programming
User level:
Intermediate
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN978-1-4302-1956-9
9 781430 219569
54999
RELATED TITLES
Pro
JPA 2
Mastering the Java

Persistence API
Mike Keith and Merrick Schincariol
Foreword by Linda DeMichiel, JPA Specification Lead
Create robust, data-driven applications with
this definitive guide to the new JPA 2
Java

EE 6
compliant
THE EXPERT’S VOICE
®
 IN JAVA

 TECHNOLOGY
Trim: 7.5 x 9.25 spine = 1.0" 536 page count
Keith
Schincariol
JPA 2
Companion
eBook Available
Pro
Java™ EE 6
compliant

this print for content only—size & color not accurate
  CYAN
  MAGENTA
  YELLOW
  BLACK
  PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Pro JPA 2: Mastering the Java


Persistence API
Dear Reader,
It’s hard to believe that over 3 years have gone by since the initial 1.0 release of
the Java™ Persistence API. In that time we have seen it go from fledgling API
to mainstream persistence standard. Along the way, many of you cut your JPA
teeth using the first edition of this book, and we’re happy we were there to help!
JPA 2.0 includes a host of new features, such as additional object-relational
mappings, more object modeling flexibility, typed queries, and a brand-new
criteria API, to name a few. With so much to talk about, we were excited to
update the book and explain all the new features, but we also included some
hints and tips to help you use the API in practice.
If you already have experience with JPA 1.0 then you should benefit from
the version tips that point out when a feature was added in 2.0. These tips
were also designed to help users who are writing to a JPA 1.0 implementation,
and are not yet able to make use of the 2.0 features.
Those of you that are new to JPA can rest assured that you were not for-
gotten. We have remained true to our original intent to take someone from
having no JPA knowledge all the way to being an advanced JPA’er. You should
be able to quickly learn in the first two chapters what you need to know to get
started. (Veteran JPA programmers might want to start at Chapter 3!) Finally,
we want to thank you for making the previous edition of this book such a suc-
cess. We are pleased that it has become the primary resource for JPA develop-
ers, and hope that you will find this edition equally valuable.
Mike Keith, JPA 2.0 Expert Group Member, and Merrick Schincariol
Authors of
Pro EJB™ 3: Java™
Persistence API
US $49.99
Shelve in
Java Programming
User level:
Intermediate
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN978-1-4302-1956-9
9 781430 219569
54999
RELATED TITLES
Pro
JPA 2
Mastering the Java

Persistence API
Mike Keith and Merrick Schincariol
Foreword by Linda DeMichiel, JPA Specification Lead
Create robust, data-driven applications with
this definitive guide to the new JPA 2
Java

EE 6
compliant
THE EXPERT’S VOICE
®
 IN JAVA

 TECHNOLOGY
Trim: 7.5 x 9.25 spine = 1.0" 536 page count
i

Pro JPA 2
Mastering the Java™ Persistence API














■ ■ ■
Mike Keith and
Merrick Schnicariol

ii

Pro JPA 2
Copyright © 2009 by Mike Keith and Merrick Schincariol
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN-13 (pbk): 978-1-4302-1956-9
ISBN-13 (electronic): 978-1-4302-1957-6
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
President and Publisher: Paul Manning
Lead Editor: Steve Anglin, Tom Welsh
Technical Reviewer: Jim Farley
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell,
Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank
Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Mary Tobin
Copy Editor: Nancy Sixsmith
Compositor: MacPS, LLC
Indexer: BIM Indexers and e-Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th
Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-
sbm.com, or visit http://www.springeronline.com.
For information on translations, please e-mail info@apress.com, or visit http://www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional
use. eBook versions and licenses are also available for most titles. For more information, reference
our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to be
caused directly or indirectly by the information contained in this work.
The source code for this book is available to readers at http://www.apress.com. You will need to
answer questions pertaining to this book in order to successfully download the code.
iii




To the memory of my father, who selflessly offered all that he had, and to my wife Darleen who has
devoted her life to helping children.—Mike

To Anthony, whose boundless creativity continues to inspire me. To Evan, whose boisterous enthusiasm
motivates me to take on new challenges. To Kate, who proves that size is no object when you have the
right attitude. I love you all.—Merrick

iv

Contents at a Glance


Contents at a Glance............................................................................................iv

Contents................................................................................................................v

Foreword.............................................................................................................xx

About the Author................................................................................................xxi

About the Technical Reviewer...........................................................................xxii

Acknowledgments............................................................................................xxiii

Preface...............................................................................................................xiv

Chapter 1: Introduction.........................................................................................1

Chapter 2: Getting Started...................................................................................17

Chapter 3: Enterprise Applications.....................................................................33

Chapter 4: Object-Relational Mapping................................................................69

Chapter 5: Collection Mapping..........................................................................107

Chapter 6: Entity Manager................................................................................131

Chapter 7: Using Queries...................................................................................179

Chapter 8: Query Language...............................................................................207

Chapter 9: Criteria API......................................................................................239

Chapter 10: Advanced Object-Relational Mapping............................................273

Chapter 11: Advanced Topics............................................................................315

Chapter 12: XML Mapping Files........................................................................371

Chapter 13: Packaging and Deployment...........................................................407

Chapter 14: Testing...........................................................................................429

Chapter 15: Migration.......................................................................................457

Index.................................................................................................................481
v

Contents


Contents at a Glance............................................................................................iv

Contents................................................................................................................v

Foreword.............................................................................................................xx


About the Author................................................................................................xxi


About the Technical Reviewer...........................................................................xxii

Acknowledgments............................................................................................xxiii

Preface.............................................................................................................xxiv


Chapter 1: Introduction.........................................................................................1
Object-Relational Mapping.............................................................................................2
The Impedance Mismatch......................................................................................................................3

Class Representation........................................................................................................................3

Relationships....................................................................................................................................5

Inheritance........................................................................................................................................7

Java Support for Persistence..........................................................................................9
Proprietary Solutions..............................................................................................................................9

JDBC......................................................................................................................................................9

Enterprise JavaBeans..........................................................................................................................10

Java Data Objects................................................................................................................................10

Why Another Standard?................................................................................................11
The Java Persistence API..............................................................................................12
History of the Specification..................................................................................................................12

EJB 3.0 and JPA 1.0........................................................................................................................12

JPA 2.0............................................................................................................................................13

JPA and You....................................................................................................................................13

Overview..............................................................................................................................................13

POJO Persistence............................................................................................................................13

Nonintrusiveness............................................................................................................................14

Object Queries.................................................................................................................................14

■ CONTENTS
vi

Mobile Entities................................................................................................................................14

Simple Configuration.......................................................................................................................15

Integration and Testability..............................................................................................................15

Summary.......................................................................................................................15

Chapter 2: Getting Started...................................................................................17
Entity Overview.............................................................................................................17
Persistability........................................................................................................................................17

Identity.................................................................................................................................................18

Transactionality....................................................................................................................................18

Granularity...........................................................................................................................................18

Entity Metadata.............................................................................................................19
Annotations..........................................................................................................................................19

XML......................................................................................................................................................19

Configuration by Exception..................................................................................................................19

Creating an Entity..........................................................................................................20
Entity Manager..............................................................................................................22
Obtaining an Entity Manager................................................................................................................23

Persisting an Entity..............................................................................................................................24

Finding an Entity..................................................................................................................................24

Removing an Entity..............................................................................................................................25

Updating an Entity................................................................................................................................26

Transactions........................................................................................................................................26

Queries.................................................................................................................................................27

Putting It All Together...................................................................................................28
Packaging It Up.............................................................................................................30
Persistence Unit...................................................................................................................................30

Persistence Archive.............................................................................................................................31

Summary.......................................................................................................................32

Chapter 3: Enterprise Applications.....................................................................33
Application Component Models....................................................................................33
Session Beans...............................................................................................................34
Stateless Session Beans......................................................................................................................35

Defining a Stateless Session Bean.................................................................................................35

Lifecycle Callbacks.........................................................................................................................37

Remote Business Interfaces...........................................................................................................38

■ CONTENTS
vii
Stateful Session Beans........................................................................................................................39

Defining a Stateful Session Bean....................................................................................................39

Lifecycle Callbacks.........................................................................................................................40

Singleton Session Beans......................................................................................................................42

Defining a Singleton Session Bean.................................................................................................42

Lifecycle Callbacks.........................................................................................................................43

Singleton Concurrency....................................................................................................................43

Message-Driven Beans.................................................................................................45
Defining a Message-Driven Bean.........................................................................................................45

Servlets.........................................................................................................................46
Dependency Management............................................................................................47
Dependency Lookup.............................................................................................................................47

Dependency Injection...........................................................................................................................49

Field Injection..................................................................................................................................49

Setter Injection................................................................................................................................50

Declaring Dependencies......................................................................................................................51

Referencing a Persistence Context.................................................................................................51

Referencing a Persistence Unit.......................................................................................................52

Referencing Enterprise JavaBeans.................................................................................................52

Referencing Server Resources........................................................................................................53

Transaction Management.............................................................................................53
Transaction Review..............................................................................................................................54

Enterprise Transactions in Java...........................................................................................................54

Transaction Demarcation................................................................................................................55

Container-Managed Transactions...................................................................................................56

Bean-Managed Transactions..........................................................................................................58

Using Java EE Components..........................................................................................60
Using a Stateless Session Bean...........................................................................................................60

Using a Stateful Session Bean.............................................................................................................60

Using a Singleton Session Bean..........................................................................................................62

Using a Message-Driven Bean.............................................................................................................62

Adding the Entity Manager...................................................................................................................63

Putting It All Together...................................................................................................64
Defining the Component......................................................................................................................64

Defining the User Interface..................................................................................................................66

Packaging It Up....................................................................................................................................66

■ CONTENTS
viii

Summary.......................................................................................................................67

Chapter 4: Object-Relational Mapping................................................................69
Persistence Annotations...............................................................................................69
Accessing Entity State..................................................................................................70
Field Access.........................................................................................................................................70

Property Access...................................................................................................................................71

Mixed Access.......................................................................................................................................71

Mapping to a Table.......................................................................................................73
Mapping Simple Types..................................................................................................74
Column Mappings................................................................................................................................75

Lazy Fetching.......................................................................................................................................76

Large Objects.......................................................................................................................................77

Enumerated Types...............................................................................................................................78

Temporal Types....................................................................................................................................80

Transient State.....................................................................................................................................80

Mapping the Primary Key..............................................................................................81
Overriding the Primary Key Column.....................................................................................................81

Primary Key Types...............................................................................................................................81

Identifier Generation............................................................................................................................82

Automatic Id Generation..................................................................................................................82

Id Generation Using a Table............................................................................................................83

Id Generation Using a Database Sequence.....................................................................................85

Id Generation Using Database Identity............................................................................................86

Relationships................................................................................................................87
Relationship Concepts.........................................................................................................................87

Roles...............................................................................................................................................87

Directionality...................................................................................................................................87

Cardinality.......................................................................................................................................88

Ordinality.........................................................................................................................................89

Mappings Overview..............................................................................................................................90

Single-Valued Associations..................................................................................................................90

Many-to-One Mappings..................................................................................................................90

Using Join Columns........................................................................................................................91

One-to-One Mappings.....................................................................................................................93

Bidirectional One-to-One Mappings................................................................................................94

Collection-Valued Associations............................................................................................................95

■ CONTENTS
ix
One-to-Many Mappings..................................................................................................................95

Many-to-Many Mappings................................................................................................................97

Using Join Tables............................................................................................................................99

Unidirectional Collection Mappings...............................................................................................100

Lazy Relationships.............................................................................................................................101

Embedded Objects......................................................................................................102
Summary.....................................................................................................................106

Chapter 5: Collection Mapping..........................................................................107
Relationships and Element Collections.......................................................................107
Using Different Collection Types.................................................................................110
Sets or Collections.............................................................................................................................111

Lists....................................................................................................................................................111

Ordering By Entity or Element Attribute........................................................................................111

Persistently Ordered Lists.............................................................................................................112

Maps..................................................................................................................................................114

Keys and Values............................................................................................................................115

Keying By Basic Type....................................................................................................................115

Keying by Entity Attribute..............................................................................................................118

Keying by Embeddable Type.........................................................................................................119

Keying by Entity............................................................................................................................123

Untyped Maps...............................................................................................................................124

Rules for Maps..............................................................................................................................125

Duplicates..........................................................................................................................................126

Null Values.........................................................................................................................................128

Best Practices.............................................................................................................128
Summary.....................................................................................................................129

Chapter 6: Entity Manager................................................................................131
Persistence Contexts..................................................................................................131
Entity Managers..........................................................................................................132
Container-Managed Entity Managers................................................................................................132

Transaction-Scoped......................................................................................................................132

Extended.......................................................................................................................................133

Application-Managed Entity Managers..............................................................................................136

Transaction Management...........................................................................................138
JTA Transaction Management...........................................................................................................138

Transaction-Scoped Persistence Contexts...................................................................................139

■ CONTENTS
x

Extended Persistence Contexts.....................................................................................................140

Application-Managed Persistence Contexts.................................................................................144

Resource-Local Transactions.............................................................................................................147

Transaction Rollback and Entity State...............................................................................................149

Choosing an Entity Manager.......................................................................................149
Entity Manager Operations.........................................................................................150
Persisting an Entity............................................................................................................................150

Finding an Entity................................................................................................................................151

Removing an Entity............................................................................................................................152

Cascading Operations........................................................................................................................153

Cascade Persist............................................................................................................................154

Cascade Remove...........................................................................................................................155

Clearing the Persistence Context.......................................................................................................156

Synchronization with the Database............................................................................156
Detachment and Merging...........................................................................................158
Detachment........................................................................................................................................159

Merging Detached Entities.................................................................................................................160

Working with Detached Entities.........................................................................................................164

Planning for Detachment..............................................................................................................166

Avoiding Detachment....................................................................................................................168

Merge Strategies...........................................................................................................................172

Summary.....................................................................................................................177

Chapter 7: Using Queries...................................................................................179
Java Persistence Query Language..............................................................................179
Getting Started...................................................................................................................................180

Filtering Results.................................................................................................................................180

Projecting Results..............................................................................................................................181

Joins Between Entities.......................................................................................................................181

Aggregate Queries.............................................................................................................................182

Query Parameters..............................................................................................................................182

Defining Queries.........................................................................................................183
Dynamic Query Definition...................................................................................................................183

Named Query Definition.....................................................................................................................185

Parameter Types.........................................................................................................187
Executing Queries.......................................................................................................188
Working with Query Results...............................................................................................................190

■ CONTENTS
xi
Untyped Results............................................................................................................................191

Optimizing Read-Only Queries......................................................................................................191

Special Result Types.....................................................................................................................192

Query Paging......................................................................................................................................193

Queries and Uncommitted Changes...................................................................................................195

Query Timeouts..................................................................................................................................198

Bulk Update and Delete..............................................................................................199
Using Bulk Update and Delete............................................................................................................199

Bulk Delete and Relationships...........................................................................................................201

Query Hints.................................................................................................................202
Query Best Practices...................................................................................................203
Named Queries..................................................................................................................................203

Report Queries...................................................................................................................................204

Vendor Hints.......................................................................................................................................204

Stateless Session Beans....................................................................................................................204

Bulk Update and Delete......................................................................................................................205

Provider Differences..........................................................................................................................205

Summary.....................................................................................................................205

Chapter 8: Query Language...............................................................................207
Introduction.................................................................................................................207
Terminology.......................................................................................................................................208

Example Data Model..........................................................................................................................208

Example Application...........................................................................................................................209

Select Queries.............................................................................................................211
SELECT Clause...................................................................................................................................212

Path Expressions...........................................................................................................................212

Entities and Objects......................................................................................................................213

Combining Expressions.................................................................................................................214

Constructor Expressions...............................................................................................................215

Inheritance and Polymorphism.....................................................................................................215

FROM Clause......................................................................................................................................216

Identification Variables.................................................................................................................216

Joins..............................................................................................................................................216

WHERE Clause....................................................................................................................................223

Input Parameters..........................................................................................................................223

Basic Expression Form..................................................................................................................223

■ CONTENTS
xii

BETWEEN Expressions..................................................................................................................224

LIKE Expressions...........................................................................................................................224

Subqueries....................................................................................................................................225

IN Expressions..............................................................................................................................226

Collection Expressions..................................................................................................................227

EXISTS Expressions.......................................................................................................................228

ANY, ALL, and SOME Expressions.................................................................................................228

Scalar Expressions.............................................................................................................................228

Literals..........................................................................................................................................229

Function Expressions....................................................................................................................230

CASE Expressions.........................................................................................................................231

ORDER BY Clause...............................................................................................................................233

Aggregate Queries......................................................................................................233
Aggregate Functions..........................................................................................................................235

AVG................................................................................................................................................235

COUNT...........................................................................................................................................235

MAX...............................................................................................................................................235

MIN................................................................................................................................................235

SUM...............................................................................................................................................235

GROUP BY Clause...............................................................................................................................236

HAVING Clause...................................................................................................................................236

Update Queries...........................................................................................................237
Delete Queries.............................................................................................................237
Summary.....................................................................................................................238

Chapter 9: Criteria API......................................................................................239
Overview.....................................................................................................................239
The Criteria API..................................................................................................................................240

Parameterized Types.........................................................................................................................241

Dynamic Queries................................................................................................................................241

Building Criteria API Queries.......................................................................................244
Creating a Query Definition................................................................................................................244

Basic Structure..................................................................................................................................246

Criteria Objects and Mutability...........................................................................................................246

Query Roots and Path Expressions....................................................................................................247

Query Roots...................................................................................................................................247

Path Expressions...........................................................................................................................248

■ CONTENTS
xiii

The SELECT Clause............................................................................................................................249

Selecting Single Expressions........................................................................................................249

Selecting Multiple Expressions.....................................................................................................250

Using Aliases.................................................................................................................................251

The FROM Clause...............................................................................................................................251

Inner and Outer Joins....................................................................................................................252

Fetch Joins....................................................................................................................................253

The WHERE Clause.............................................................................................................................254

Building Expressions..........................................................................................................................254

Predicates.....................................................................................................................................257

Literals..........................................................................................................................................258

Parameters....................................................................................................................................258

Subqueries....................................................................................................................................258

In Expressions...............................................................................................................................261

Case Expressions..........................................................................................................................262

Function Expressions....................................................................................................................264

The ORDER BY Clause........................................................................................................................264

The GROUP BY and HAVING Clauses..................................................................................................265

Strongly Typed Query Definitions................................................................................265
The Metamodel API............................................................................................................................265

Strongly Typed API Overview.............................................................................................................267

The Canonical Metamodel..................................................................................................................268

Using the Canonical Metamodel...................................................................................................269

Generating the Canonical Metamodel...........................................................................................270

Choosing the Right Type of Query......................................................................................................271

Summary.....................................................................................................................271

Chapter 10: Advanced Object-Relational Mapping............................................273
Table and Column Names...........................................................................................273
Complex Embedded Objects.......................................................................................275
Advanced Embedded Mappings.........................................................................................................275

Overriding Embedded Relationships..................................................................................................276

Compound Primary Keys.............................................................................................278
Id Class...............................................................................................................................................278

Embedded Id Class.............................................................................................................................280

Derived Identifiers.......................................................................................................281
Basic Rules for Derived Identifiers.....................................................................................................282

■ CONTENTS
xiv

Shared Primary Key...........................................................................................................................283

Multiple Mapped Attributes................................................................................................................284

Using EmbeddedId.............................................................................................................................286

Advanced Mapping Elements......................................................................................288
Read-Only Mappings..........................................................................................................................288

Optionality..........................................................................................................................................289

Advanced Relationships..............................................................................................289
Using Join Tables...............................................................................................................................290

Avoiding Join Tables..........................................................................................................................291

Compound Join Columns...................................................................................................................292

Orphan Removal.................................................................................................................................294

Mapping Relationship State...............................................................................................................295

Multiple Tables............................................................................................................297
Inheritance..................................................................................................................300
Class Hierarchies...............................................................................................................................300

Mapped Superclasses...................................................................................................................301

Transient Classes in the Hierarchy...............................................................................................303

Abstract and Concrete Classes.....................................................................................................303

Inheritance Models............................................................................................................................304

Single-Table Strategy...................................................................................................................304

Joined Strategy.............................................................................................................................307

Table-per-Concrete-Class Strategy..............................................................................................309

Mixed Inheritance..............................................................................................................................311

Summary.....................................................................................................................313

Chapter 11: Advanced Topics............................................................................315
SQL Queries................................................................................................................315
Native Queries versus JDBC...............................................................................................................316

Defining and Executing SQL Queries..................................................................................................318

SQL Result Set Mapping.....................................................................................................................320

Mapping Foreign Keys..................................................................................................................321

Multiple Result Mappings.............................................................................................................321

Mapping Column Aliases...............................................................................................................321

Mapping Scalar Result Columns...................................................................................................322

Mapping Compound Keys.............................................................................................................324

Mapping Inheritance.....................................................................................................................325

Parameter Binding.............................................................................................................................326

■ CONTENTS
xv
Lifecycle Callbacks.....................................................................................................326
Lifecycle Events.................................................................................................................................326

PrePersist and PostPersist............................................................................................................326

PreRemove and PostRemove........................................................................................................327

PreUpdate and PostUpdate...........................................................................................................327

PostLoad.......................................................................................................................................327

Callback Methods...............................................................................................................................327

Enterprise Contexts.......................................................................................................................329

Entity Listeners..................................................................................................................................329

Attaching Entity Listeners to Entities............................................................................................329

Default Entity Listeners.................................................................................................................331

Inheritance and Lifecycle Events.......................................................................................................331

Inheriting Callback Methods.........................................................................................................331

Inheriting Entity Listeners.............................................................................................................332

Lifecycle Event Invocation Order...................................................................................................332

Validation....................................................................................................................335
Using Constraints...............................................................................................................................336

Invoking Validation.............................................................................................................................337

Validation Groups...............................................................................................................................338

Creating New Constraints..................................................................................................................340

Constraint Annotations..................................................................................................................340

Constraint Implementation Classes..............................................................................................341

Validation in JPA................................................................................................................................342

Enabling Validation............................................................................................................................343

Setting Lifecycle Validation Groups...................................................................................................343

Concurrency................................................................................................................344
Entity Operations................................................................................................................................344

Entity Access......................................................................................................................................345

Refreshing Entity State...............................................................................................345
Locking.......................................................................................................................348
Optimistic Locking.............................................................................................................................348

Versioning.....................................................................................................................................349

Advanced Optimistic Locking Modes............................................................................................350

Recovering from Optimistic Failures.............................................................................................355

Pessimistic Locking...........................................................................................................................358

Pessimistic Locking Modes...........................................................................................................358

Pessimistic Scope.........................................................................................................................360

■ CONTENTS
xvi

Pessimistic Timeouts....................................................................................................................360

Recovering From Pessimistic Failures..........................................................................................361

Caching.......................................................................................................................361
Sorting Through the Layers................................................................................................................361

Shared Cache.....................................................................................................................................363

Static Configuration of the Cache.................................................................................................365

Dynamic Cache Management.......................................................................................................366

Utility Classes..............................................................................................................368
PersistenceUtil...................................................................................................................................368

PersistenceUnitUtil.............................................................................................................................368

Summary.....................................................................................................................369

Chapter 12: XML Mapping Files........................................................................371
The Metadata Puzzle...................................................................................................372
The Mapping File........................................................................................................373
Disabling Annotations........................................................................................................................373

xml-mapping-metadata-complete................................................................................................374

metadata-complete.......................................................................................................................374

Persistence Unit Defaults...................................................................................................................375

schema.........................................................................................................................................376

catalog..........................................................................................................................................376

delimited-identifiers......................................................................................................................376

access...........................................................................................................................................377

cascade-persist............................................................................................................................377

entity-listeners..............................................................................................................................378

Mapping File Defaults........................................................................................................................378

package........................................................................................................................................379

schema.........................................................................................................................................379

catalog..........................................................................................................................................380

access...........................................................................................................................................380

Queries and Generators.....................................................................................................................381

sequence-generator......................................................................................................................381

table-generator.............................................................................................................................382

named-query.................................................................................................................................382

named-native-query.....................................................................................................................383

sql-result-set-mapping.................................................................................................................384

Managed Classes and Mappings.......................................................................................................385

■ CONTENTS
xvii
Attributes......................................................................................................................................385

Tables............................................................................................................................................386

Identifier Mappings.......................................................................................................................387

Simple Mappings..........................................................................................................................389

Relationship and Collection Mappings..........................................................................................391

Embedded Object Mappings.........................................................................................................398

Inheritance Mappings...................................................................................................................401

Lifecycle Events............................................................................................................................404

Entity Listeners.............................................................................................................................404

Summary.....................................................................................................................406

Chapter 13: Packaging and Deployment...........................................................407
Configuring Persistence Units.....................................................................................407
Persistence Unit Name.......................................................................................................................408

Transaction Type................................................................................................................................408

Persistence Provider..........................................................................................................................408

Data Source.......................................................................................................................................409

Mapping Files.....................................................................................................................................410

Managed Classes...............................................................................................................................411

Local Classes................................................................................................................................411

Classes in Mapping Files..............................................................................................................412

Explicitly Listed Classes................................................................................................................412

Additional JARs of Managed Classes............................................................................................413

Shared Cache Mode...........................................................................................................................413

Validation Mode.................................................................................................................................414

Adding Vendor Properties..................................................................................................................414

Building and Deploying...............................................................................................415
Deployment Classpath.......................................................................................................................415

Packaging Options.............................................................................................................................416

EJB JAR.........................................................................................................................................416

Web Archive..................................................................................................................................418

Persistence Archive......................................................................................................................419

Persistence Unit Scope......................................................................................................................420

Outside the Server......................................................................................................420
Configuring the Persistence Unit.......................................................................................................421

Transaction Type...........................................................................................................................421

Data Source..................................................................................................................................421

Providers.......................................................................................................................................422

■ CONTENTS
xviii

Listing the Entities........................................................................................................................422

Specifying Properties at Runtime......................................................................................................423

System Classpath..............................................................................................................................423

Schema Generation.....................................................................................................423
Unique Constraints.............................................................................................................................424

Null Constraints..................................................................................................................................425

String-Based Columns.......................................................................................................................425

Floating Point Columns......................................................................................................................426

Defining the Column...........................................................................................................................426

Summary.....................................................................................................................427

Chapter 14: Testing...........................................................................................429
Testing Enterprise Applications..................................................................................429
Terminology.......................................................................................................................................430

Testing Outside the Server.................................................................................................................431

Test Frameworks...............................................................................................................................432

Unit Testing.................................................................................................................433
Testing Entities..................................................................................................................................433

Testing Entities in Components.........................................................................................................434

The Entity Manager in Unit Tests.......................................................................................................436

Integration Testing......................................................................................................439
Using the Entity Manager...................................................................................................................439

Test Setup and Teardown.............................................................................................................441

Switching Configurations for Testing............................................................................................442

Minimizing Database Connections................................................................................................444

Components and Persistence............................................................................................................445

Transaction Management.............................................................................................................445

Container-Managed Entity Managers...........................................................................................450

Other Services...............................................................................................................................452

Using an Embedded EJB Container for Integration Testing..........................................................453

Best Practices.............................................................................................................455
Summary.....................................................................................................................455

Chapter 15: Migration.......................................................................................457
Migrating from CMP Entity Beans...............................................................................457
Scoping the Challenge.......................................................................................................................458

Entity Bean Conversion......................................................................................................................459

Converting the Business Interface................................................................................................459

■ CONTENTS
xix
Converting the Home Interface.....................................................................................................463

Migrating from JDBC...................................................................................................467
Migrating from Other ORM Solutions..........................................................................468
Leveraging Design Patterns........................................................................................469
Transfer Object..................................................................................................................................469

Fine-Grained Transfer Objects......................................................................................................469

Coarse-Grained Transfer Objects..................................................................................................471

Session Façade..................................................................................................................................472

Data Access Object............................................................................................................................474

Business Object.................................................................................................................................478

Fast Lane Reader...............................................................................................................................479

Active Record.....................................................................................................................................479

Summary.....................................................................................................................480

Index.................................................................................................................481
■ CONTENTS
xx

Foreword

When the Java Persistence API was first released as part of Enterprise JavaBeans 3.0 in 2006, it was
quickly received as one of the most exciting technologies of Java EE 5. Like EJB 3.0, of which it was a part,
JPA 1.0 was focused on both function and ease of use, leveraging Java language annotations and sensible
defaulting to provide convenient configuration.
JPA 1.0, however, was not just a much-needed replacement for the heavy-weight entity “bean”
components of earlier EJB releases, although that was its initial reason for existence. As a more general-
purpose object-relational mapping facility, it was quickly recognized as such, and was expanded at the
request of the community to support use in Java SE environments as well as in the other Java EE
container types. As a “specification within a specification”, it had thus already outgrown its parent by the
time it was released.
Aside from its query language, there is very little in the core functionality of JPA that reveals its
origins as part of the EJB 3.0 work. The true origins of JPA, of course, lie in the world of object-relational
mapping products and projects, such as TopLink (now well past its tenth anniversary), Hibernate, and
JDO, many of whose lead architects—such as Mike Keith—were among the prime contributors to JPA.
However, JPA 1.0 represented only one facet of the work (and workload) of the EJB 3.0 expert group,
and, while it covered the core functionality needed for O/R mapping, it was not nearly as complete an
API as many of the products and projects which provided its first implementations.
The task of JPA 2.0 has been to solidify the standard, to expand its scope, and thus to provide
developers with greater portability for both simple and sophisticated applications. Like JPA 1.0, it has
been driven by experience from technology already in the field and steered by the requests from
members of the community.
The JPA 2.0 specification and APIs have more than doubled in size with this release. This reflects
additions to support many modeling constructs natural to Java developers, expansion of the
standardized mapping options, an object-based criteria query API, a metamodel API, support for
automatic validation, support for pessimistic locking, and much more.
In this book, Mike Keith and Merrick Schincariol present a comprehensive guide to the Java
Persistence API. As authors, they bring a depth of experience in O/R mapping technology that is rarely
equaled, as well as—in Mike’s case—years of experience in shaping JPA itself.
This book covers all aspects of the Java Persistence API. It is both thorough and accessible, and both
entertaining and exacting. It not only introduces the reader to all aspects of the API and discusses how to
use its constructs most effectively, it also explains what goes on under the covers and how to avoid
portability pitfalls when working with different vendor implementations. Throughout the book, the
authors provide carefully detailed explanations of the workings of object-relational mapping so that the
reader is left not only with a knowledge of the features of Java Persistence but also with a deeper
understanding of how it works. I hope you will enjoy it as much as I have.
Linda DeMichiel
Specification Lead, Java Persistence 2.0
Sun Microsystems
Santa Clara, California

■ CONTENTS
xxi

About the Author

■ Mike Keith was the co-specification lead for JPA 1.0 and an active member of the
JPA 2.0 expert group. He sits on a number of other Java Community Process expert
groups, including JSR 316, the Java EE 6 platform specification, and the Enterprise
Expert Group (EEG) in the OSGi Alliance. He holds a Masters degree in Computer
Science from Carleton University and has 20 years experience in persistence and
distributed systems research and practice. He has written papers and articles on JPA
and spoken at numerous conferences around the world. He is employed as an
architect at Oracle in Ottawa, Canada, and lives with his wife Darleen, their four kids,
and his wife’s dog.
■ Merrick Schincariol is a consulting engineer at Oracle, specializing in middleware
technologies. He has a Bachelor of Science degree in computer science from
Lakehead University and has more than a decade of experience in enterprise
software development. He spent some time consulting in the pre-Java enterprise and
business intelligence fields before moving on to write Java and J2EE applications. His
experience with large-scale systems and data warehouse design gave him a mature
and practiced perspective on enterprise software, which later propelled him
into doing EJB container implementation work. He was a lead engineer for Oracle’s
EJB 3.0 offering.


■ CONTENTS
xxii

About the Technical Reviewer

■ Jim Farley is a technology strategist, architect, manager and author. He currently
serves as a Director of Technology for Pearson Education, driving the development
of new educational service platforms.

Jim is also a lecturer in the computer science department of the Harvard Extension
School, and writes and speaks frequently on enterprise technology and other
strategic topics. He is the author of Practical JBoss Seam Projects (Apress), co-author
of Java Enterprise in a Nutshell (O’Reilly), and author of Java Distributed Computing
(O’Reilly).

■ CONTENTS
xxiii
Acknowledgments
Mike Keith
I would like to thank all of the friends and colleagues who offered to help in any way they could. You all
know who you are! Linda DeMichiel and Lance Andersen were very helpful going through the chapters
and finding bugs when it wasn’t necessarily convenient for them to be doing so. Jim Farley provided
great technical reviewing, and Tom Welsh always managed to have helpful suggestions in each and every
chapter. Richard Dal Porto and Mary Tobin were firm in trying to keep us to a schedule, but
understanding when the laws of physics couldn’t be broken. Michael O’Brien spent many long nights
translating our chapterware into running code, and probably got more than he bargained for! Thanks to
Doug Clarke and Shaun Smith for spreading the word that a JPA book was available, and to Dennis
Leung for offering his full support of my writing this book. Lastly, I thank my kids, Cierra, Ariana, Jeremy
and Emma, some of whom had to wait for a paragraph to be done before getting help with their
homework, and Darleen, who always did her best to take up the slack when her slacker couldn’t keep up.
Merrick Schincariol
I want to thank my wife, Natalie, and my children, Anthony, Evan and Kate for enduring through yet
another one of my little projects. It was far more than we bargained for, and their constant love and
support kept me going through it all. Mike was once again a fantastic partner for this project and