Pro JPA 2 (eBook)
XXVI, 500 Seiten
Apress (Verlag)
978-1-4302-1957-6 (ISBN)
Pro JPA 2 introduces, explains, and demonstrates how to use the Java Persistence API (JPA). JPA provides Java developers with both the knowledge and insight needed to write Java applications that access relational databases through JPA.
Authors Mike Keith and Merrick Schincariol take a hands-on approach to teaching by giving examples to illustrate each concept of the API and showing how it is used in practice.
All of the examples use a common model from an overriding sample application, giving readers a context from which to start and helping them to understand the examples within an already familiar domain.After completing the book, you will have a full understanding and be able to successfully code applications using JPA. The book also serves as a reference guide during initial and later JPA application experiences.
- Hands-on examples for all the aspects of the JPA specification, based on the reference implementation of this specification
- A special section on migration to JPA
- Expert insight about various aspects of the API and when they are useful
- Portability hints to provide increased awareness of the potential for non-portable JPA code
Mike Keith wasthe co-specification lead for JPA 1.0 and a member of the JPA 2.0 and JPA 2.1expert groups. He sits on a number of other Java Community Process expertgroups and the Enterprise Expert Group (EEG) in the OSGi Alliance. He holds aMasters degree in Computer Science from Carleton University, and has over 20years experience in persistence and distributed systems research and practice.He has written papers and articles on JPA and spoken at numerous conferencesaround the world. He is employed as an architect at Oracle in Ottawa, Canada,and is married with four kids and two dogs.
Pro JPA 2 introduces, explains, and demonstrates how to use the Java Persistence API (JPA). JPA provides Java developers with both the knowledge and insight needed to write Java applications that access relational databases through JPA.Authors Mike Keith and Merrick Schincariol take a hands on approach to teaching by giving examples to illustrate each concept of the API and showing how it is used in practice.All of the examples use a common model from an overriding sample application, giving readers a context from which to start and helping them to understand the examples within an already familiar domain. After completing the book, you will have a full understanding and be able to successfully code applications using JPA. The book also serves as a reference guide during initial and later JPA application experiences. Hands-on examples for all the aspects of the JPA specification, based on the reference implementation of this specification A special section on migration to JPA Expert insight about various aspects of the API and when they are useful Portability hints to provide increased awareness of the potential for non portable JPA code
Mike Keith wasthe co-specification lead for JPA 1.0 and a member of the JPA 2.0 and JPA 2.1expert groups. He sits on a number of other Java Community Process expertgroups and the Enterprise Expert Group (EEG) in the OSGi Alliance. He holds aMasters degree in Computer Science from Carleton University, and has over 20years experience in persistence and distributed systems research and practice.He has written papers and articles on JPA and spoken at numerous conferencesaround the world. He is employed as an architect at Oracle in Ottawa, Canada,and is married with four kids and two dogs.
Title Page 1
Copyright Page 2
Contents at a Glance 4
Table of Contents 5
Foreword 20
About the Author 21
About the Technical Reviewer 22
Acknowledgments 23
Mike Keith 23
Merrick Schincariol 23
Preface 24
This Book Is For You 24
Code Examples 25
Contacting Us 25
Chapter 1: Introduction 26
Object-Relational Mapping 27
The Impedance Mismatch 28
Class Representation 28
Relationships 30
Inheritance 32
Java Support for Persistence 34
Proprietary Solutions 34
JDBC 34
Enterprise JavaBeans 35
Java Data Objects 35
Why Another Standard? 36
The Java Persistence API 37
History of the Specification 37
EJB 3.0 and JPA 1.0 37
JPA 2.0 38
JPA and You 38
Overview 38
POJO Persistence 39
Nonintrusiveness 39
Object Queries 39
Mobile Entities 39
Simple Configuration 40
Integration and Testability 40
Summary 40
Chapter 2: Getting Started 42
Entity Overview 42
Persistability 43
Identity 43
Transactionality 43
Granularity 43
Entity Metadata 44
Annotations 44
XML 44
Configuration by Exception 45
Creating an Entity 45
Entity Manager 47
Obtaining an Entity Manager 48
Persisting an Entity 49
Finding an Entity 49
Removing an Entity 50
Updating an Entity 51
Transactions 51
Queries 52
Putting It All Together 53
Packaging It Up 55
Persistence Unit 55
Persistence Archive 56
Summary 57
Chapter 3: Enterprise Applications 58
Application Component Models 58
Session Beans 59
Stateless Session Beans 60
Defining a Stateless Session Bean 60
Lifecycle Callbacks 62
Remote Business Interfaces 63
Stateful Session Beans 64
Defining a Stateful Session Bean 64
Lifecycle Callbacks 66
Singleton Session Beans 67
Defining a Singleton Session Bean 67
Lifecycle Callbacks 68
Singleton Concurrency 68
Message-Driven Beans 70
Defining a Message-Driven Bean 70
Servlets 71
Dependency Management 72
Dependency Lookup 72
Dependency Injection 74
Field Injection 74
Setter Injection 75
Declaring Dependencies 76
Referencing a Persistence Context 76
Referencing a Persistence Unit 77
Referencing Enterprise JavaBeans 77
Referencing Server Resources 78
Transaction Management 78
Transaction Review 79
Enterprise Transactions in Java 80
Transaction Demarcation 80
Container-Managed Transactions 81
Bean-Managed Transactions 83
UserTransaction 83
Using Java EE Components 85
Using a Stateless Session Bean 85
Using a Stateful Session Bean 85
Using a Singleton Session Bean 87
Using a Message-Driven Bean 87
Adding the Entity Manager 88
Putting It All Together 89
Defining the Component 89
Defining the User Interface 91
Packaging It Up 92
Summary 92
Chapter 4: Object-Relational Mapping 94
Persistence Annotations 94
Accessing Entity State 95
Field Access 95
Property Access 96
Mixed Access 96
Mapping to a Table 98
Mapping Simple Types 99
Column Mappings 100
Lazy Fetching 101
Large Objects 102
Enumerated Types 103
Temporal Types 105
Transient State 105
Mapping the Primary Key 106
Overriding the Primary Key Column 106
Primary Key Types 106
Identifier Generation 107
Automatic Id Generation 107
Id Generation Using a Table 108
Id Generation Using a Database Sequence 110
Id Generation Using Database Identity 111
Relationships 112
Relationship Concepts 112
Roles 112
Directionality 112
Cardinality 114
Ordinality 114
Mappings Overview 115
Single-Valued Associations 115
Many-to-One Mappings 115
Using Join Columns 116
One-to-One Mappings 118
Bidirectional One-to-One Mappings 119
Collection-Valued Associations 120
One-to-Many Mappings 120
Many-to-Many Mappings 122
Using Join Tables 124
Unidirectional Collection Mappings 125
Lazy Relationships 126
Embedded Objects 127
Summary 131
Chapter 5: Collection Mapping 132
Relationships and Element Collections 132
Using Different Collection Types 135
Sets or Collections 136
Lists 136
Ordering By Entity or Element Attribute 136
Persistently Ordered Lists 137
Maps 139
Keys and Values 140
Keying By Basic Type 140
Keying by Entity Attribute 143
Keying by Embeddable Type 144
Overriding Embeddable Attributes 146
Keying by Entity 148
Untyped Maps 149
Rules for Maps 150
Duplicates 151
Null Values 153
Best Practices 153
Summary 154
Chapter 6: Entity Manager 155
Persistence Contexts 155
Entity Managers 156
Container-Managed Entity Managers 156
Transaction-Scoped 156
Extended 157
Application-Managed Entity Managers 160
Transaction Management 162
JTA Transaction Management 162
Transaction-Scoped Persistence Contexts 163
Extended Persistence Contexts 165
Persistence Context Collision 166
Persistence Context Inheritance 167
Application-Managed Persistence Contexts 168
Resource-Local Transactions 171
Transaction Rollback and Entity State 173
Choosing an Entity Manager 174
Entity Manager Operations 174
Persisting an Entity 174
Finding an Entity 175
Removing an Entity 176
Cascading Operations 177
Cascade Persist 178
Cascade Remove 179
Clearing the Persistence Context 180
Synchronization with the Database 181
Detachment and Merging 183
Detachment. 183
Merging Detached Entities 185
Working with Detached Entities 188
Planning for Detachment 190
Triggering Lazy Loading 190
Configuring Eager Loading 191
Avoiding Detachment 192
Transaction View 192
Entity Manager per Request 194
Merge Strategies 196
Session Façade 196
Edit Session 198
Summary 201
Chapter 7: Using Queries 202
Java Persistence Query Language 202
Getting Started 203
Filtering Results 204
Projecting Results 204
Joins Between Entities 204
Aggregate Queries 205
Query Parameters 205
Defining Queries 206
Dynamic Query Definition 206
Named Query Definition 208
Parameter Types 210
Executing Queries 211
Working with Query Results 213
Untyped Results 214
Optimizing Read-Only Queries 214
Special Result Types 215
Query Paging 216
Queries and Uncommitted Changes 218
Query Timeouts 221
Bulk Update and Delete 222
Using Bulk Update and Delete 222
Bulk Delete and Relationships 224
Query Hints 225
Query Best Practices 226
Named Queries 226
Report Queries 227
Vendor Hints 227
Stateless Session Beans 227
Bulk Update and Delete 228
Provider Differences 228
Summary 228
Chapter 8: Query Language 230
Introduction 230
Terminology 231
Example Data Model 231
Example Application 232
Select Queries 234
SELECT Clause 235
Path Expressions 235
Entities and Objects 236
Combining Expressions 237
Constructor Expressions 238
Inheritance and Polymorphism 238
FROM Clause 239
Identification Variables 239
Joins 239
Inner Joins 240
JOIN Operator and Collection Association Fields 240
JOIN Operator and Single-Valued Association Fields 242
Join Conditions in the WHERE Clause 243
Multiple Joins 243
Map Joins 243
Outer Joins 244
Fetch Joins 245
WHERE Clause 246
Input Parameters 246
Basic Expression Form 246
BETWEEN Expressions 247
LIKE Expressions 247
Subqueries 248
IN Expressions 249
Collection Expressions 250
EXISTS Expressions 251
ANY, ALL, and SOME Expressions 251
Scalar Expressions 251
Literals 252
Function Expressions 253
CASE Expressions 254
ORDER BY Clause 256
Aggregate Queries 256
Aggregate Functions 258
AVG 258
COUNT 258
MAX 258
MIN 258
SUM 258
GROUP BY Clause 259
HAVING Clause 259
Update Queries 260
Delete Queries 260
Summary 261
Chapter 9: Criteria API 262
Overview 262
The Criteria APi 263
Parameterized Types 264
Dynamic Queries 264
Building Criteria API Queries 267
Creating a Query Definition 267
Basic Structure 269
Criteria Objects and Mutability 269
Query Roots and Path Expressions 270
Query Roots 270
Path Expressions 271
The SELECT Clause 272
Selecting Single Expressions 272
Selecting Multiple Expressions 273
Using Aliases 274
The FROM Clause 274
Inner and Outer Joins 275
Fetch Joins 276
The WHERE Clause 277
Building Expressions 277
Predicates 280
Literals 281
Parameters 281
Subqueries 281
In Expressions 284
Case Expressions 285
Function Expressions 287
The ORDER BY Clause 287
The GROUP BY and HAVING Clauses 288
Strongly Typed Query Definitions 288
The Metamodel APi 288
Strongly Typed API Overview 290
The Canonical Metamodel 291
Using the Canonical Metamodel 292
Generating the Canonical Metamodel 293
Choosing the Right Type of Query 294
Summary 294
Chapter 10: Advanced Object-Relational Mapping 295
Table and Column Names 295
Complex Embedded Objects 297
Advanced Embedded Mappings 297
Overriding Embedded Relationships 298
Compound Primary Keys 300
Id Class 300
Embedded Id Class 302
Derived Identifiers 303
Basic Rules for Derived Identifiers 304
Shared Primary Key 305
Multiple Mapped Attributes 306
Using Embeddedld 308
Advanced Mapping Elements 310
Read-Only Mappings 310
Optionality 311
Advanced Relationships 311
Using Join Tables 312
Avoiding Join Tables 313
Compound Join Columns 314
Orphan Removal 316
Mapping Relationship State 317
Multiple Tables 319
Inheritance 322
Class Hierarchies 322
Mapped Superclasses 323
Transient Classes in the Hierarchy 325
Abstract and Concrete Classes 325
Inheritance Models 326
Single-Table Strategy 326
Discriminator Column 327
Discriminator Value 327
Joined Strategy 329
Table-per-Concrete-Class Strategy 331
Mixed Inheritance 333
Summary 335
Chapter 11: Advanced Topics 337
SQl Queries 337
Native Queries versus JDBC 338
Defining and Executing SQl Queries 340
SQl Result Set Mapping 342
Mapping Foreign Keys 343
Multiple Result Mappings 343
Mapping Column Aliases 343
Mapping Scalar Result Columns 344
Mapping Compound Keys 346
Mapping Inheritance 347
Parameter Binding 348
Lifecycle Callbacks 348
Lifecycle Events 348
Pre Persist and PostPersist 348
PreRemove and PostRemove 349
PreUpdate and PostUpdate 349
Post Load 349
Callback Methods 349
Enterprise Contexts 351
Entity Listeners 351
Attaching Entity Listeners to Entities 351
Default Entity Listeners 353
Inheritance and Lifecycle Events 353
Inheriting Callback Methods 353
Inheriting Entity Listeners 354
Lifecycle Event Invocation Order 354
Validation 357
Using Constraints 358
Invoking Validation 359
Validation Groups 360
Creating New Constraints 362
Constraint Annotations 362
Constraint Implementation Classes 363
Validation in JPA 364
Enabling Validation 365
Setting Lifecycle Validation Groups 365
Concurrency 366
Entity Operations 366
Entity Access 367
Refreshing Entity State 367
Locking 370
Optimistic Locking 370
Versioning 371
Advanced Optimistic Locking Modes 372
Optimistic Read Locking 373
Optimistic Write Locking 375
Recovering from Optimistic Failures 377
Pessimistic Locking 380
Pessimistic Locking Modes 380
Pessimistic Write Locking 380
Pessimistic Read Locking 382
Pessimistic Forced Increment Locking 382
Pessimistic Scope 382
Pessimistic Timeouts 382
Recovering From Pessimistic Failures 383
Caching 383
Sorting Through the Layers 383
Shared Cache 385
Static Configuration of the Cache 387
Dynamic Cache Management 388
Utility Classes 390
PersistenceUtil 390
PersistenceUnitUtil 390
Summary 391
Chapter 12: XML Mapping Files 393
The Metadata Puzzle 394
The Mapping File 395
Disabling Annotations 395
xml-mapping-metadata-complete 396
metadata-complete 396
Persistence Unit Defaults 397
schema 398
catalog 398
delimited-identifiers 398
access 399
cascade-persist 399
entity-listeners 400
Mapping File Defaults 400
package 401
schema 401
catalog 402
access 402
Queries and Generators 403
sequence-generator 403
table-generator 404
named-query 404
named-native-query 405
sql-result-set-mapping 406
Managed Classes and Mappings 407
Attributes 407
Tables 408
table 408
secondary-table 408
Identifier Mappings 409
id 409
embedded-id 410
id-class 411
Simple Mappings 411
basic 411
transient 412
version 413
Relationship and Collection Mappings 413
many-to-one 414
one-to-many 415
one-to-one 416
many-to-many 418
element-collection 419
Embedded Object Mappings 420
embedded 420
attribute-override 421
association-override 422
Inheritance Mappings 423
inheritance 423
discriminator-column 424
discriminator-value 424
attribute-override and association-override 425
Lifecycle Events 426
Entity Listeners 426
entity-listeners 426
exclude-default-listeners 428
exclude-superclass-listeners 428
Summary 428
Chapter 13: Packaging and Deployment 429
Configuring Persistence Units 429
Persistence Unit Name 430
Transaction Type 430
Persistence Provider 430
Data Source 431
Mapping Files 432
Managed Classes 433
Local Classes 433
Classes in Mapping Files 434
Explicitly Listed Classes 434
Additional JARs of Managed Classes 435
Shared Cache Mode 435
Validation Mode 436
Adding Vendor Properties 436
Building and Deploying 437
Deployment Classpath 437
Packaging Options 438
EJB JAR 438
Web Archive 440
Persistence Archive 441
Persistence Unit Scope 442
Outside the Server 442
Configuring the Persistence Unit 443
Transaction Type 443
Data Source 443
Providers 444
Listing the Entities 444
Specifying Properties at Runtime 445
System Classpath 445
Schema Generation 445
Unique Constraints 446
Null Constraints 447
String-Based Columns 447
Floating Point Columns 448
Defining the Column 448
Summary 449
Chapter 14: Testing 451
Testing Enterprise Applications 451
Terminology 452
Testing Outside the Server 453
Test Frameworks 454
Unit Testing 455
Testing Entities 455
Testing Entities in Components 456
The Entity Manager in Unit Tests 458
Integration Testing 461
Using the Entity Manager 461
Test Setup and Teardown 463
Switching Configurations for Testing 464
Minimizing Database Connections 466
Components and Persistence 467
Transaction Management 467
When to Use Transactions 467
Container-Managed Transactions 468
Bean-Managed Transactions 469
Container-Managed Entity Managers 472
Other Services 474
Using an Embedded EJB Container for Integration Testing 475
Best Practices 477
Summary 477
Chapter 15: Migration 479
Migrating from CMP Entity Beans 479
Scoping the Challenge 480
Entity Bean Conversion 481
Converting the Business Interface 481
Migrating Properties 481
Migrating Business Methods 482
Migrating Container-Managed Relationships 483
Converting the Home Interface 485
Migrating Home Methods 486
Creating the Façade 487
Migrating from JDBC 489
Migrating from Other ORM Solutions 490
Leveraging Design Patterns 491
Transfer Object 491
Fine-Grained Transfer Objects 491
Coarse-Grained Transfer Objects 493
Session FaGade 494
Data Access Object 496
Business Object 500
Fast Lane Reader 501
Active Record 501
Summary 502
Index 503
Erscheint lt. Verlag | 28.1.2011 |
---|---|
Zusatzinfo | XXVI, 500 p. |
Verlagsort | Berkeley |
Sprache | englisch |
Themenwelt | Informatik ► Programmiersprachen / -werkzeuge ► Java |
Mathematik / Informatik ► Informatik ► Theorie / Studium | |
Mathematik / Informatik ► Informatik ► Web / Internet | |
Schlagworte | Database • Deployment • Java • Java EE • XML |
ISBN-10 | 1-4302-1957-2 / 1430219572 |
ISBN-13 | 978-1-4302-1957-6 / 9781430219576 |
Haben Sie eine Frage zum Produkt? |
Größe: 2,4 MB
DRM: Digitales Wasserzeichen
Dieses eBook enthält ein digitales Wasserzeichen und ist damit für Sie personalisiert. Bei einer missbräuchlichen Weitergabe des eBooks an Dritte ist eine Rückverfolgung an die Quelle möglich.
Dateiformat: PDF (Portable Document Format)
Mit einem festen Seitenlayout eignet sich die PDF besonders für Fachbücher mit Spalten, Tabellen und Abbildungen. Eine PDF kann auf fast allen Geräten angezeigt werden, ist aber für kleine Displays (Smartphone, eReader) nur eingeschränkt geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür einen PDF-Viewer - z.B. den Adobe Reader oder Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür einen PDF-Viewer - z.B. die kostenlose Adobe Digital Editions-App.
Zusätzliches Feature: Online Lesen
Dieses eBook können Sie zusätzlich zum Download auch online im Webbrowser lesen.
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich