Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13...

86
20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved i Table of Contents – EJB 3.1 and JPA 2 Enterprise JavaBeans and the Java Persistence API _________________________ 1 Workshop Overview _______________________________________________________________ 2 Workshop Objectives ______________________________________________________________ 3 Workshop Agenda _________________________________________________________________ 4 Course Prerequisites _______________________________________________________________ 5 Labs ____________________________________________________________________________ 6 Session 1: Introduction __________________________________________________ 7 Lesson Objectives _________________________________________________________________ 8 Overview __________________________________________________________________ 9 What is EJB _____________________________________________________________________ 10 EJB Goals ______________________________________________________________________ 11 EJB Goals (continued)_____________________________________________________________ 12 Types of Enterprise JavaBeans ______________________________________________________ 13 Java Persistence API ______________________________________________________________ 14 EJB and Java EE (Enterprise Edition) _________________________________________________ 15 EJB in Java EE Architecture ________________________________________________________ 16 SOA and EJB____________________________________________________________________ 17 SOA with Web Services and EJB ____________________________________________________ 18 EJB 3 ____________________________________________________________________ 19 EJB 3 Overview__________________________________________________________________ 20 EJB 2.x Problems ________________________________________________________________ 21 EJB 3.0 Goals ___________________________________________________________________ 22 EJB 3.1 Goals ___________________________________________________________________ 24 Session Bean Usage_______________________________________________________________ 25 Session Bean Usage_______________________________________________________________ 26 Persistent Entity Usage ____________________________________________________________ 27 MDB Usage_____________________________________________________________________ 28 Lab 1.1 – Setting Up the Environment ____________________________________________ 29 Review Questions ________________________________________________________________ 30 Lesson Summary _________________________________________________________________ 31 Session 2: Session Beans ________________________________________________ 33 Lesson Objectives ________________________________________________________________ 34 Session Bean Overview______________________________________________________ 35 What are Session Beans____________________________________________________________ 36 Stateless Session Beans (SLSB) _____________________________________________________ 37 Stateful Session Beans (SFSB) ______________________________________________________ 38 Session Beans Can Be Distributed ___________________________________________________ 39 Defining a Session Bean ___________________________________________________________ 40 Stateless Session Bean Definition ____________________________________________________ 41 Calculator Remote Business Interface_________________________________________________ 42 Remote and Local Business Interfaces ________________________________________________ 43 Calculator Bean Local Business Interface______________________________________________ 44 A Brief Note on Annotations________________________________________________________ 45 How Annotations Work____________________________________________________________ 46 Annotation Definition _____________________________________________________________ 47 Using Annotations ________________________________________________________________ 48 What Else Is Needed ______________________________________________________________ 49 Packaging and Deployment __________________________________________________ 50 EVALUATION COPY Unauthorized reproduction or distribution is prohibited.

Transcript of Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13...

Page 1: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved i

Table of Contents – EJB 3.1 and JPA 2

Enterprise JavaBeans and the Java Persistence API _________________________ 1 Workshop Overview _______________________________________________________________ 2 Workshop Objectives ______________________________________________________________ 3 Workshop Agenda_________________________________________________________________ 4 Course Prerequisites _______________________________________________________________ 5 Labs ____________________________________________________________________________ 6

Session 1: Introduction __________________________________________________ 7 Lesson Objectives _________________________________________________________________ 8

Overview __________________________________________________________________ 9 What is EJB_____________________________________________________________________ 10 EJB Goals ______________________________________________________________________ 11 EJB Goals (continued)_____________________________________________________________ 12 Types of Enterprise JavaBeans ______________________________________________________ 13 Java Persistence API ______________________________________________________________ 14 EJB and Java EE (Enterprise Edition)_________________________________________________ 15 EJB in Java EE Architecture ________________________________________________________ 16 SOA and EJB____________________________________________________________________ 17 SOA with Web Services and EJB ____________________________________________________ 18

EJB 3 ____________________________________________________________________ 19 EJB 3 Overview__________________________________________________________________ 20 EJB 2.x Problems ________________________________________________________________ 21 EJB 3.0 Goals ___________________________________________________________________ 22 EJB 3.1 Goals ___________________________________________________________________ 24 Session Bean Usage_______________________________________________________________ 25 Session Bean Usage_______________________________________________________________ 26 Persistent Entity Usage ____________________________________________________________ 27 MDB Usage_____________________________________________________________________ 28

Lab 1.1 – Setting Up the Environment ____________________________________________ 29 Review Questions ________________________________________________________________ 30 Lesson Summary _________________________________________________________________ 31

Session 2: Session Beans ________________________________________________ 33 Lesson Objectives ________________________________________________________________ 34

Session Bean Overview______________________________________________________ 35 What are Session Beans____________________________________________________________ 36 Stateless Session Beans (SLSB) _____________________________________________________ 37 Stateful Session Beans (SFSB) ______________________________________________________ 38 Session Beans Can Be Distributed ___________________________________________________ 39 Defining a Session Bean ___________________________________________________________ 40 Stateless Session Bean Definition ____________________________________________________ 41 Calculator Remote Business Interface_________________________________________________ 42 Remote and Local Business Interfaces ________________________________________________ 43 Calculator Bean Local Business Interface______________________________________________ 44 A Brief Note on Annotations________________________________________________________ 45 How Annotations Work____________________________________________________________ 46 Annotation Definition _____________________________________________________________ 47 Using Annotations________________________________________________________________ 48 What Else Is Needed ______________________________________________________________ 49

Packaging and Deployment __________________________________________________ 50

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 2: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved ii

JEE Packaging___________________________________________________________________ 51 ejb-jar File ______________________________________________________________________ 52 Deployment Descriptor (DD) _______________________________________________________ 53 Deployment Descriptors in EJB 3 ____________________________________________________ 54 ejb-jar File Structure ______________________________________________________________ 55 Enterprise Archive (ear file) ________________________________________________________ 56 Application.xml File ______________________________________________________________ 57 Web Application Structure - JEE 6 ___________________________________________________ 58 Server Deployment _______________________________________________________________ 59 EJB Container ___________________________________________________________________ 60 The EJB Container _______________________________________________________________ 61 Server Deployment _______________________________________________________________ 62

Lab 2.1 – Write and Deploy an EJB ______________________________________________ 63 JNDI Overview ____________________________________________________________ 64

How do Remote Clients Get EJB Access ______________________________________________ 65 JNDI – Java Naming and Directory Interface ___________________________________________ 66 EJB Container Binds a Reference Into JNDI____________________________________________ 67 Client Looks Up Reference In JNDI __________________________________________________ 68 JNDI Tree Structure ______________________________________________________________ 69 JNDI Tree Structure ______________________________________________________________ 70 JNDI API Overview ______________________________________________________________ 71 JNDI API_______________________________________________________________________ 72 The Context Interface _____________________________________________________________ 73 The InitialContext Class ___________________________________________________________ 74 Specifying the InitialContext Properties _______________________________________________ 75 Using JNDI _____________________________________________________________________ 76

EJB Remote Client _________________________________________________________ 77 Client View of a Session Bean ______________________________________________________ 78 EJB 3.1 - Portable JNDI Names _____________________________________________________ 79 Portable JNDI Name Example ______________________________________________________ 80 Client Invocation of a Session EJB ___________________________________________________ 81 Running a Client _________________________________________________________________ 82

Lab 2.2 – Write and Run an EJB Client ___________________________________________ 83 Review Questions ________________________________________________________________ 84 Lesson Summary _________________________________________________________________ 85

Session 3: Additional EJB Capabilities ____________________________________ 87 Lesson Objectives ________________________________________________________________ 88

Dependency Injection _______________________________________________________ 89 Dependency Injection _____________________________________________________________ 90 The JavaTunes Online Music Store___________________________________________________ 91 An EJB Referencing Another EJB ___________________________________________________ 92 CatalogMaintenance ______________________________________________________________ 93 Injection of CatalogMaintenance_____________________________________________________ 94 What is Happening _______________________________________________________________ 95

Lab 3.1 – Dependency Injection __________________________________________________ 96 Deployment Descriptors_____________________________________________________ 97

More about Deployment Descriptors__________________________________________________ 98 The XML Deployment Descriptor____________________________________________________ 99 Sample Standard Deployment Descriptor _____________________________________________ 100

The EJB Environment _____________________________________________________ 101 Issues With Obtaining Resources ___________________________________________________ 102 More Information on EJB References ________________________________________________ 103

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 3: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved iii

Referencing Resources External to EAR______________________________________________ 104 References & Deployment Descriptor Usage __________________________________________ 105 Resolving a JNDI Name __________________________________________________________ 106 Resolving a JNDI Name __________________________________________________________ 107 Simple Environment Entries _______________________________________________________ 108 Simple Environment Entry Example _________________________________________________ 109 Declaring Simple Environment Entries _______________________________________________ 110 Setter Injection__________________________________________________________________ 111 Resource Manager Connection Factories _____________________________________________ 112 Resource Manager Connection Factories _____________________________________________ 113 DataSource Reference Example - Bean_______________________________________________ 114 DataSource Reference Example - DD ________________________________________________ 115 More on the Enterprise Bean Environment ____________________________________________ 116 The Environment is a Level of Indirection ____________________________________________ 117 Looking Up Resources in the Environment____________________________________________ 118 Looking up Via EJBContext _______________________________________________________ 119 Looking up via JNDI API _________________________________________________________ 120 More on the @Stateless Annotation _________________________________________________ 121 @Stateless Example _____________________________________________________________ 122 More on the @EJB Annotation _____________________________________________________ 123 More on the @Resource Annotation _________________________________________________ 124 Deployment Descriptor vs Annotation _______________________________________________ 125

Lab 3.2 – Simple Environment Entry ____________________________________________ 126 Stateless Session Bean Lifecycle & Interceptors ________________________________ 127

Overview ______________________________________________________________________ 128 Stateless Session Bean State Diagram________________________________________________ 129 Life Cycle of SSB _______________________________________________________________ 130 Client Call of a Stateless SB Method ________________________________________________ 131 Interceptors ____________________________________________________________________ 132 Business Method Interceptors ______________________________________________________ 133 Business Method Interceptors Example ______________________________________________ 134 InvocationContext Interface Details _________________________________________________ 135 Interceptor Method Details ________________________________________________________ 136 Interceptor Class ________________________________________________________________ 137 Using Interceptor Classes _________________________________________________________ 138 Method Level Interceptors_________________________________________________________ 139 Lifecycle Callback Interceptors_____________________________________________________ 140 Lifecycle Interceptor in the Bean Class_______________________________________________ 141 Lifecycle Interceptor in a Separate Class _____________________________________________ 142

Lab 3.3 – Interceptors _________________________________________________________ 143 Asynchronous Methods, Singleton Session Beans _______________________________ 144

Overview ______________________________________________________________________ 145 Singleton Session Bean ___________________________________________________________ 146 Singleton Initialization ___________________________________________________________ 147 Singleton Concurrency ___________________________________________________________ 148 Asynchronous Method Invocations __________________________________________________ 149 Using Future ___________________________________________________________________ 150

Stateful Session Beans _____________________________________________________ 151 Stateful Session Bean (SFSB) Overview______________________________________________ 152 Coding a Stateful Session Bean_____________________________________________________ 153 Stateful Session Bean Removal_____________________________________________________ 154 Stateful Session Bean Clients ______________________________________________________ 155 Servlet Use of Stateful Session Beans ________________________________________________ 156 Servlet Use of Stateful Session Beans ________________________________________________ 157

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 4: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved iv

Stateful Session Passivation/Activation ______________________________________________ 158 When to Use Stateful Session Beans _________________________________________________ 159 @PrePassivate and @PostActivate Callbacks__________________________________________ 160 Stateful Session Bean State Diagram ________________________________________________ 161

Lab 3.4 – Stateful Session Beans ________________________________________________ 162 The Timer Service_________________________________________________________ 163

Overview ______________________________________________________________________ 164 Programmatic Timers ____________________________________________________________ 165 The javax.ejb.Timer Interface ______________________________________________________ 166 The javax.ejb.TimerService Interface ________________________________________________ 167 TimerService Methods (contd.)_____________________________________________________ 168 Timer Example _________________________________________________________________ 169 How the Timer Works ____________________________________________________________ 170 ScheduleExpression: Calendar-Based Timers __________________________________________ 171 ScheduleExpression Example ______________________________________________________ 172 Issues with Programmatic Timers ___________________________________________________ 173 Automatic Timers - javax.ejb.Schedule_______________________________________________ 174 @Schedule Details ______________________________________________________________ 175

Lab 3.5 – Timers _____________________________________________________________ 176 Review Questions _______________________________________________________________ 177 Lesson Summary ________________________________________________________________ 178

Session 4: Message-Driven Beans________________________________________ 181 Lesson Objectives _______________________________________________________________ 182

Overview of Messaging Systems _____________________________________________ 183 What is Messaging?______________________________________________________________ 184 Loose Coupling _________________________________________________________________ 185 When is Messaging Used?_________________________________________________________ 186 Two Messaging Models___________________________________________________________ 187 Publish/Subscribe - Illustrated______________________________________________________ 188 More on Publish/Subscribe ________________________________________________________ 189 Point-to-Point - Illustrated_________________________________________________________ 190 More on Point-to-Point (P2P) ______________________________________________________ 191 Message Delivery - Push versus Pull_________________________________________________ 192

Overview of JMS API______________________________________________________ 193 What is Java Message Service? _____________________________________________________ 194 API Structure___________________________________________________________________ 195 JMS Interfaces__________________________________________________________________ 196 Administered Objects ____________________________________________________________ 197 Administered Objects and JNDI - Illustrated __________________________________________ 198 Client Workflow ________________________________________________________________ 199 Queue Producer Client Example ____________________________________________________ 200 Queue Producer Client Example ____________________________________________________ 201 Synchronous Queue Consumer Client________________________________________________ 202 Asynchronous Queue Consumer Client_______________________________________________ 203 Message Listener Example ________________________________________________________ 204 JMS Message Types _____________________________________________________________ 205 Message Header Fields ___________________________________________________________ 206

Message-Driven Beans _____________________________________________________ 207 JEE Message Producers and Consumers ______________________________________________ 208 Message-Driven Bean (MDB) Overview _____________________________________________ 209 Goals of Message-Driven Beans ____________________________________________________ 210 Simple MDB Example____________________________________________________________ 211 MDB Consumption of a Message ___________________________________________________ 212

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 5: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved v

@MessageDriven Details _________________________________________________________ 213 Activation Configuration Properties _________________________________________________ 214 Specifying a Destination for an MDB ________________________________________________ 215 Specifying a Destination Using a DD ________________________________________________ 216

Message-Driven Bean Lifecycle______________________________________________ 217 Lifecycle Overview ______________________________________________________________ 218 MDB State Diagram _____________________________________________________________ 219 Interceptor Methods______________________________________________________________ 220

Lab 4.1 – Message Driven Bean _________________________________________________ 221 Review Questions _______________________________________________________________ 222 Lesson Summary ________________________________________________________________ 223

Session 5: Transactions and Security _____________________________________ 224 Lesson Objectives _______________________________________________________________ 225

Transaction Definition _____________________________________________________ 226 Transaction Overview ____________________________________________________________ 227 Transaction Lifecycle ____________________________________________________________ 228 Transactions Clarify Systems ______________________________________________________ 229

Transactional System Overview _____________________________________________ 230 Overview of a Transactional System_________________________________________________ 231 Transactional System Components __________________________________________________ 232 Transactional System Components __________________________________________________ 233 Transactional Object _____________________________________________________________ 234 EJB Transaction Support__________________________________________________________ 235

Transactions in EJB _______________________________________________________ 236 EJB Declarative Transaction Management ____________________________________________ 237 Transactional Scope______________________________________________________________ 238 EJB Transaction Attributes ________________________________________________________ 239 Specifying Transaction Attributes ___________________________________________________ 240 Specifying Transaction Attributes ___________________________________________________ 241 NOTSUPPORTED ______________________________________________________________ 242 SUPPORTS ____________________________________________________________________ 243 REQUIRED____________________________________________________________________ 244 REQUIRESNEW _______________________________________________________________ 245 MANDATORY _________________________________________________________________ 246 NEVER _______________________________________________________________________ 247 Beans Have a Say in Transactions___________________________________________________ 248 Beans Can be Notified of Transaction Status __________________________________________ 249 Transaction Example _____________________________________________________________ 250 Transaction Attributes – Some Choices ______________________________________________ 251 Transaction Attributes - Some Choices _______________________________________________ 252 Explicit / Bean-Managed Transactions _______________________________________________ 253 UserTransaction & Bean-Managed Example __________________________________________ 254 Transaction Isolation Levels _______________________________________________________ 255 Transaction Isolation Levels Usage__________________________________________________ 256 Multi-process TX and Two Phase Commit ____________________________________________ 257

Lab 5.1 – Transactions ________________________________________________________ 258 Security in EJB ___________________________________________________________ 259

Security Requirements____________________________________________________________ 260 JEE security____________________________________________________________________ 261 Roles _________________________________________________________________________ 262 JEE Security Overview ___________________________________________________________ 263 EJB Security Overview ___________________________________________________________ 264

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 6: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved vi

Annotation Example _____________________________________________________________ 265 Example: Roles and Method Permissions _____________________________________________ 266 Annotation Example _____________________________________________________________ 267 Same Example With Annotations ___________________________________________________ 268 Authentication __________________________________________________________________ 269 Programmatic Security ___________________________________________________________ 270 Example of Programmatic Security__________________________________________________ 271 Transport Level Security with SSL __________________________________________________ 272

Lab 5.2 – Security ____________________________________________________________ 273 Review Questions _______________________________________________________________ 274 Lesson Summary ________________________________________________________________ 275 Lesson Summary ________________________________________________________________ 276

Session 6: Exception Handling and Best Practices _________________________ 277 Lesson Objectives _______________________________________________________________ 278

Exception Handling _______________________________________________________ 279 Overview of Exceptions __________________________________________________________ 280 Exception Hierarchy _____________________________________________________________ 281 Application Exceptions in EJB _____________________________________________________ 282 Defining Application Exceptions ___________________________________________________ 283 Application Exception Example ____________________________________________________ 284 Container Handling of Application Exception _________________________________________ 285 Bean Throwing of Application Exception_____________________________________________ 286 Client Handling of Application Exceptions____________________________________________ 287 System Exceptions Indicate Failure__________________________________________________ 288 Container Handling of System Exception _____________________________________________ 289 Client Handling of System Exceptions _______________________________________________ 290

EJB 3 Best Practices _______________________________________________________ 291 When To Use EJB _______________________________________________________________ 292 Keep Business Interfaces Coarse Grained_____________________________________________ 293 Session Façade Structure__________________________________________________________ 294 Use Container-Managed Transactions________________________________________________ 295 Transaction Duration _____________________________________________________________ 296 Local and Remote Business Interface ________________________________________________ 297 Tuning ________________________________________________________________________ 298 Session Bean Tuning _____________________________________________________________ 299 Clustering _____________________________________________________________________ 300 Clustering Session Beans__________________________________________________________ 301 Review Questions _______________________________________________________________ 302 Lesson Summary ________________________________________________________________ 303

Session 7: Introduction to the Java Persistence API (JPA 2) _________________ 305 Lesson Objectives _______________________________________________________________ 306

JPA Overview ____________________________________________________________ 307 The Issues with Persistence Layers __________________________________________________ 308 Object-Relational Mapping (ORM) Issues ____________________________________________ 309 Java Persistence API Overview_____________________________________________________ 310 JPA Benefits ___________________________________________________________________ 311 Java Persistence Environments _____________________________________________________ 312 JPA Architecture – High Level View ________________________________________________ 313 JPA Architecture – Programming View ______________________________________________ 314

Mapping a Simple Class____________________________________________________ 315 Entity Classes __________________________________________________________________ 316 Entity Class Requirements_________________________________________________________ 317

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 7: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved vii

An Example Entity Class__________________________________________________________ 318 javax.persistence.Entity Annotation _________________________________________________ 319 The Event Class_________________________________________________________________ 320 javax.persistence.Id and ID property_________________________________________________ 321 Field Access or Property Access ____________________________________________________ 322 The EVENTS Table _____________________________________________________________ 323 Generated Id Property ____________________________________________________________ 324 Mapping Properties ______________________________________________________________ 325 Basic Mapping Types ____________________________________________________________ 326 Temporal (Date/Time) Mappings ___________________________________________________ 327 Persisting to the Database _________________________________________________________ 328

Lab 7.1 – Mapping an Entity Class ______________________________________________ 329 Entity Manager and Persistence Context ______________________________________ 330

The Persistence Unit _____________________________________________________________ 331 persistence.xml _________________________________________________________________ 332 Classes included in a persistence unit ________________________________________________ 333 The EntityManager & Persistence Context ____________________________________________ 334 EntityManager Interface __________________________________________________________ 335 Obtaining an Entity Manager ______________________________________________________ 336 Injecting an EntityManager ________________________________________________________ 337 Container-Managed Entity Manger __________________________________________________ 338 Retrieving Persistent Objects_______________________________________________________ 339

Lab 7.2 – Using an Entity Class _________________________________________________ 340 More About Mappings _____________________________________________________ 341

Default Mappings _______________________________________________________________ 342 @Basic and @Column ___________________________________________________________ 343 Field and Property Access _________________________________________________________ 344 Mapping Enums_________________________________________________________________ 345 Review Questions _______________________________________________________________ 346 Lesson Summary ________________________________________________________________ 347

Session 8: Updates and Queries _________________________________________ 349 Lesson Objectives _______________________________________________________________ 350

Inserting and Updating ____________________________________________________ 351 Persisting a New Entity ___________________________________________________________ 352 Persisting a New Entity Example ___________________________________________________ 353 Synchronization To the Database ___________________________________________________ 354 Updating a Persistent Instance______________________________________________________ 355 Removing an Instance ____________________________________________________________ 356 Detached Entities________________________________________________________________ 357

Lab 8.1 – Inserting and Updating _______________________________________________ 358 Querying and Java Persistence Query Language (JPQL) ________________________ 359

Java Persistence Query Language ___________________________________________________ 360 JPQL Basics – SELECT Statement __________________________________________________ 361 Querying and the Query Interface ___________________________________________________ 362 Executing a Query _______________________________________________________________ 363 JPA 2 – Generic Query Enhancements _______________________________________________ 364 JPA 2 – Generic Query Enhancements _______________________________________________ 365 Other Query Methods ____________________________________________________________ 366 Where Clause___________________________________________________________________ 367 JPQL Operators and Expressions ___________________________________________________ 368 Query Parameters _______________________________________________________________ 369 Using Query Parameters __________________________________________________________ 370 Named Queries _________________________________________________________________ 371

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 8: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved viii

Named Queries _________________________________________________________________ 372 Lab 8.2 – Basic Querying ______________________________________________________ 373

Criteria API (JPA 2)_______________________________________________________ 374 Criteria Overview _______________________________________________________________ 375 A Simple Criteria Example (1 of 3)__________________________________________________ 376 Path Expressions ________________________________________________________________ 379 WHERE Clauses ________________________________________________________________ 380 Typed Path Expressions___________________________________________________________ 381 Typed Path Expressions___________________________________________________________ 382 Combining Predicates (and/or) _____________________________________________________ 383 Additional Criteria API Capabilities _________________________________________________ 384

[Optional] Lab 8.3 – Criteria Query _____________________________________________ 385 The Persistence Lifecycle ___________________________________________________ 386

The Persistence Lifecycle _________________________________________________________ 387 JPA Entity States ________________________________________________________________ 388 Transient and Persistent State ______________________________________________________ 389 Detached and Removed State ______________________________________________________ 390 JPA Object States and Transitions___________________________________________________ 391 The Persistence Context __________________________________________________________ 392 Persistence Context Lifespan_______________________________________________________ 393 Persistence Context Propagation ____________________________________________________ 394 The Persistence Context as Cache ___________________________________________________ 395 Persistence Context and Object Identity ______________________________________________ 396 Synchronization To the Database ___________________________________________________ 397 Flushing the Entity Manager _______________________________________________________ 398 Yes, It's Complicated_____________________________________________________________ 399

Versioning / Optimistic Locking _____________________________________________ 400 Optimistic Locking ______________________________________________________________ 401 Using a Detached Instance ________________________________________________________ 402 Using a Detached Instance Example _________________________________________________ 403 Using a Detached Instance Example _________________________________________________ 404 Versioning _____________________________________________________________________ 405 Version Property in Java Class _____________________________________________________ 406 Optimistic Locking Example_______________________________________________________ 407 Locking Objects_________________________________________________________________ 408

[Optional] Lab 8.4 – Versioning_________________________________________________ 409 Review Questions _______________________________________________________________ 410 Lesson Summary ________________________________________________________________ 411

Session 9: Entity Relationships __________________________________________ 413 Lesson Objectives _______________________________________________________________ 414

Relationships Overview ____________________________________________________ 415 Object Relationships _____________________________________________________________ 416 Characteristics of Relationships ____________________________________________________ 417 Directionality___________________________________________________________________ 418 Directionality___________________________________________________________________ 419 Characteristics of Relationships ____________________________________________________ 420

Mapping Relationships_____________________________________________________ 421 Mappings Overview _____________________________________________________________ 422 Unidirectional Many-To-One Relationship____________________________________________ 423 The Table Structure – Many-To-One ________________________________________________ 424 The Owning Side________________________________________________________________ 425 @JoinColumn __________________________________________________________________ 426

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 9: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved ix

Using the Relationship ___________________________________________________________ 427 Bidirectional One-To-Many Relationship _____________________________________________ 428 Mapping the One-To-Many Relationship _____________________________________________ 429 Managing the Bidirectional Relationship _____________________________________________ 430 More on the Inverse Side__________________________________________________________ 431 More on the Collection Declaration _________________________________________________ 432 Other Collection Types ___________________________________________________________ 433 Cascading Operations ____________________________________________________________ 434 Transitive Persistence ____________________________________________________________ 435 The cascade element _____________________________________________________________ 436

Lab 9.1 – Relationships ________________________________________________________ 437 Bidirectional One-To-One Relationship ______________________________________________ 438 Bidirectional One-To-One Relationship ______________________________________________ 439 Orphan Removal (JPA 2) _________________________________________________________ 440 Many-To-Many Relationship ______________________________________________________ 441 Defining Many-To-Many Relationship _______________________________________________ 442 Mapping Many-To-Many Relationships ______________________________________________ 443 Specifying the Join Table _________________________________________________________ 444 Choosing Cascade Behavior _______________________________________________________ 445 Lazy and Eager Loading __________________________________________________________ 446 Queries Across Relationships ______________________________________________________ 447 OUTER and FETCH JOIN ________________________________________________________ 448 FETCH JOIN Example ___________________________________________________________ 449 Joins using Criteria API___________________________________________________________ 450

Lab 9.2 – Working With Relationships ___________________________________________ 451 Mapping Inheritance ______________________________________________________ 452

Entity Inheritance _______________________________________________________________ 453 Entity Inheritance _______________________________________________________________ 454 Details of Entity Inheritance _______________________________________________________ 455 Single-Table Strategy ____________________________________________________________ 456 Entity Definitions for Single-Table __________________________________________________ 457 Sample Table Entries_____________________________________________________________ 458 Single-Table: Pros and Cons _______________________________________________________ 459 Joined (Table per Subclass)________________________________________________________ 460 Entity Definitions for Joined _______________________________________________________ 461 Joined: Pros and Cons ____________________________________________________________ 462 Table per Concrete Class__________________________________________________________ 463

Lab 9.3 – Working With Inheritance_____________________________________________ 464 Embedded Objects ________________________________________________________ 465

Using Embedded Objects _________________________________________________________ 466 Embeddable Class _______________________________________________________________ 467 Reusing Embeddable Classes ______________________________________________________ 468 Overriding Embedded Class Attributes _______________________________________________ 469

Compound Primary Keys __________________________________________________ 470 Compound Primary Keys _________________________________________________________ 471 Compound Key With Embedded Id Class_____________________________________________ 472 Using an Embedded Id Class_______________________________________________________ 473 Compound Key With Id Class______________________________________________________ 474 Compound Key With Id Class______________________________________________________ 475

Element Collections (JPA 2) ________________________________________________ 476 Element Collections______________________________________________________________ 477 Modeling a Collection of String Elements ____________________________________________ 478 Mapping an Element Collection (Basic Type) _________________________________________ 479

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 10: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

20120715 Copyright © 2004-12 LearningPatterns Inc. All rights reserved x

Using an Element Collection_______________________________________________________ 480 Collections of Embeddable Components______________________________________________ 481 Mapping Collections of Embeddables________________________________________________ 482 Review Questions _______________________________________________________________ 483 Review Questions _______________________________________________________________ 484 Lesson Summary ________________________________________________________________ 485

Session 10: [Optional] Additional Java Persistence Capabilities ___________________ 489 Lesson Objectives _______________________________________________________________ 490

More on Querying_________________________________________________________ 491 Projection Queries _______________________________________________________________ 492 Aggregate Queries _______________________________________________________________ 493 Aggregate Query Examples________________________________________________________ 494 Bulk Update and Delete___________________________________________________________ 495 Native SQL Queries _____________________________________________________________ 496

Extended Persistence Contexts ______________________________________________ 497 Stateful Session Beans with Entity State ______________________________________________ 498 Extended Persistence Context ______________________________________________________ 499 Issues with Extended Persistence Context_____________________________________________ 500

XML Mapping Files _______________________________________________________ 501 XML Mapping Files _____________________________________________________________ 502 A Simple Entity Class ____________________________________________________________ 503 JPA XML Mapping File __________________________________________________________ 504 JPA XML Mapping File - Mapping Entities ___________________________________________ 505 JPA XML Mapping File - Named Queries ____________________________________________ 506

Java Persistence with Java SE_______________________________________________ 507 Using JPA with Java SE __________________________________________________________ 508 Java SE APIs ___________________________________________________________________ 509 Example of JPA in Java SE ________________________________________________________ 510

Java Persistence Best Practices ______________________________________________ 511 Primary Key Considerations _______________________________________________________ 512 Use Named Queries______________________________________________________________ 513 Use Lazy/Eager Loading Appropriately ______________________________________________ 514 Be Aware of Transaction Semantics _________________________________________________ 515 Encapsulate JPA Code____________________________________________________________ 516 Use Report Queries Where Applicable _______________________________________________ 517 Optimize Read-Only/Mostly Data Access_____________________________________________ 518 Paging Data ____________________________________________________________________ 519 Consider Going Outside of Java Persistence ___________________________________________ 520 Know Your Provider Implementation ________________________________________________ 521

Resources (EJB3 and JPA) _________________________________________________ 522 Resources______________________________________________________________________ 523

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 11: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 120120715

Fast Track to EJB 3.1 and JPA 2

Enterprise JavaBeans and the

Java Persistence API

The Java Developer Education Series

Java, EJB, Enterprise JavaBeans and all Java-based trademarks are registered trademarks of Oracle, Inc

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 12: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 220120715

Fast Track to EJB 3.1 and JPA 2

Workshop Overview

This course provides a thorough introduction to Enterprise JavaBeans V3.1, including– The needs EJB is designed to address– The basic concepts and architecture– Thorough coverage of the EJB API and details on its use– Thorough coverage of the Java Persistence API V2 (JPA 2)– Design principles for correct usage

The workshop consists of at least 50% hands-on lab exercises, including a series of labs designed to exercise all important concepts– Most of the labs follow a common fictional case study -

JavaTunes, an online music store• CDs (Item table), Inventory (Inventory table) and others

Preface

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 13: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 320120715

Fast Track to EJB 3.1 and JPA 2

Workshop Objectives

At completion you should be able to

– Understand how EJB relates to the rest of Java/Java EE

– Understand EJB concepts and architecture

– Be familiar with the EJB API, including the Java Persistence API(JPA)

– Be able to write and use EJBs

– Be familiar with the JPA API, and be able to write and use persistent entities, including advanced capabilities like relationships and inheritance

– Understand the tradeoffs involving EJB

– Understand important design principles for EJB

Preface

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 14: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 420120715

Fast Track to EJB 3.1 and JPA 2

Workshop Agenda

Session 1: Introduction to EJB

Session 2: Session Bean Architecture and API

Session 3: Additional EJB Capabilities

Session 4: Message-Driven Bean Architecture and API

Session 5:Transactions and Security

Session 6: Exceptions and Best Practices

Session 7: Java Persistence API 2 (Entity Beans) Intro

Session 8: Java Persistence API Inserts and Queries

Session 9: Java Persistence API Associations

Session 10: Java Persistence API Additional Capabilities

Preface

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 15: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 520120715

Fast Track to EJB 3.1 and JPA 2

Course Prerequisites

Proficiency in Java and Object-Oriented programming

General knowledge of Java EE (Enterprise Edition)

Knowledge of relational databases

Preface

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 16: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2004-13 LearningPatterns Inc. All rights reserved. 620120715

Fast Track to EJB 3.1 and JPA 2

Labs

The workshop has numerous hands-on lab exercises, structured as a series of brief labs – Many follow a common fictional case study called JavaTunes

• An online music store– There is a placeholder slide for each lab in the manual– The detailed lab instructions are at the end of the manual

Setup zip files are provided with skeleton code for the labs– Students add code focused on the topic they're working with– There is a solution zip with completed lab code

The end of a lab is marked with a stop like this one:

Lab

STOP

Preface

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 17: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 720120715

Fast Track to EJB 3.1 and JPA 2

Session 1: Introduction

OverviewEJB 3.1

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 18: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 820120715

Fast Track to EJB 3.1 and JPA 2

Lesson Objectives

Gain a high level understanding of EJB and EJB architecture

Understand how EJB fits into the Java EE architecture

Understand how EJB relates to other technologies

Become acquainted with EJB 3.1, its goals, and the problems with earlier versions

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 19: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 920120715

Fast Track to EJB 3.1 and JPA 2

Overview

OverviewEJB 3.1

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 20: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1020120715

Fast Track to EJB 3.1 and JPA 2

What is EJB

EJB is a framework for creating server-side components that are:– Transactional, Distributed, Portable, Reliable, Secure, Scalable– It simplifies the building of multi-tier distributed object

applications– EJB is a technology to create business-tier components for these

kinds of applications

EJB provides a server-side framework for providing a core set of system services to Java components– Services such as low-level transaction and state management,

multi-threading, and connection pooling

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 21: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1120120715

Fast Track to EJB 3.1 and JPA 2

EJB Goals

Provide a standard distributed component architecture for Java applications– Allowing easy creation of distributed business applications– Portable across many vendors (write once, run anywhere)– Fitting into the Java EE (Enterprise Edition) architecture– Enabling the use of third-party development tools– Generally meant for creating business tier components

Relieve developers from managing transactions, threads, security, resource management, while still providing access to low-level APIs– These kinds of issues are generally taken care of by the EJB

framework

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 22: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1220120715

Fast Track to EJB 3.1 and JPA 2

EJB Goals (continued)

Provide a persistence framework to simplify Object-Relational Mapping (ORM)

– The issue of mapping a set of (Java) objects to information in arelational database is complex

– The data is in different forms– Going from one form to the other is difficult, and writing the code

is tedious

Persistent entities provide a framework to automate the mapping of Java objects to relational data– A mapping is defined via metadata, and the framework

generates the JDBC code to work with the data

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 23: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1320120715

Fast Track to EJB 3.1 and JPA 2

Types of Enterprise JavaBeans

Session Beans provide a business service– Distributed, transactional– Bean instances live in a software environment called the EJB

container– The container manages the lifecycle of instances, as well as

distributed access, transactions, etc.

Message Driven Beans (MDB) integrate EJB with messaging (JMS) systems– An MDB is an asynchronous message consumer– It consumes messages from a queue or topic– Makes asynchronous processing of incoming messages on the

server simpler– Allows for concurrent processing of a stream of messages by

means of container managed pooling

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 24: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1420120715

Fast Track to EJB 3.1 and JPA 2

Java Persistence API

The brand new Java Persistence API defines a Java persistence framework

Persistent Entities provide Object-Relational Mapping(ORM) capabilities– Persistent entities are lightweight persistent domain objects– Primary concern is mapping objects to relational data– Persistent entities are not distributed objects, though they may

be accessed in a distributed way using a session bean façade

Persistent entities are not really "Entity Beans"– They are a separate part of the specification now– Can be used separately from other parts of EJB– In a new package, javax.persistence, not in javax.ejb

The Java Persistence API is a separate part of the same specification defining EJB (JSR-220)– It is required for all EJB containers– However, it can also be used separately if only Java Persistence is needed

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 25: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1520120715

Fast Track to EJB 3.1 and JPA 2

EJB and Java EE (Enterprise Edition)

Java EE is an architecture for building multi-tier enterprise applications– Umbrella for many other Java technologies including:– EJB, Servlets/JSP, JMS, RMI …

EJB serves as the distributed component technology and persistence framework for Java EE– Generally, EJB is used on the server side– It is often invoked from the Web tier, but may be invoked by thick

clients (e.g. Swing clients)– It can also be used in Service Oriented Architectures (SOA)

Java EE was previously known as J2EE– With the release of Java 5 / Java EE 5, the 2 was dropped from the names

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 26: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1620120715

Fast Track to EJB 3.1 and JPA 2

application server

client

client

EJB in Java EE Architecture

Web clients communicate via HTTPRich clients can communicate via HTTP or RMI

DB server

data-base

presentationbusiness

persistence

SwingGUI

HTTPbrowser

RMI

HTTP

servletsJSPs

SessionEJB

PersistentEntity

This architecture may be attractive because you can support bothWeb browser clients and Swing clients, and do so in several different ways.

– Web browser clients interact with the EJB business tier indirectly, via the servlet/JSP presentation tier.

– Swing clients can generate HTTP requests to the servlet/JSP presentation tier or can interact directly with the EJB businesstier. You might want to do this to reuse an existing servlet/JSP interface or to use HTTP to get through a firewall.

We will talk about MDB later

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 27: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1720120715

Fast Track to EJB 3.1 and JPA 2

SOA and EJB

SOA (Service Oriented Architecture) is an important basis for enterprise architecturesBased on providing resources on a network– As independent services independent of their implementation– Results in loosely coupled architecture

EJB can support SOA in multiple ways– The services can be exposed directly as a session EJB

• SOA is usually thought of in terms of Web Services (e.g. SOAP), but EJB may be a useful alternative in some cases

• This usually requires Java clients– A Web Service can be implemented using EJB

• Web Services are just a façade for exposing a service• The service has to be implemented in some way – either as an EJB

or as a regular Java object

Choosing to use EJB in a service oriented architecture is entirely valid– Web Services add a layer of complexity and inefficiency– If you don't need the advantages of Web Services, then don't use them

In fact, you can even invoke EJB from non-Java clients– This uses CORBA– It's not really a practical architecture unless you're already using a CORBA architecture

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 28: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1820120715

Fast Track to EJB 3.1 and JPA 2

SOAP/HTTP

application server

SOA with Web Services and EJB

Java Client

Web Services

Web servicesbusiness

WebServicesServlet

Another popular Java EE architectureProvides loosely coupled access via standard protocols

SOAP/HTTP

EJB

.NET Client

Web Services

In this type of architecture, SOAP/HTTP is used as the communication protocol, and the service is implemented using EJB

Servlets are used purely to support SOAP over HTTP, and are not really involved in presentation layer aspects

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 29: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 1920120715

Fast Track to EJB 3.1 and JPA 2

EJB 3

OverviewEJB 3

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 30: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2020120715

Fast Track to EJB 3.1 and JPA 2

EJB 3 Overview

Complete reworking of EJB specification– Major differences from EJB 2.x– Some areas have changed completely

Uses Java annotations heavily– Reduces the use of XML configuration files (Deployment

Descriptor), and can eliminate them

Persistence is completely different from earlier releases– Total overhaul of EJB persistence– Persistent entities much lighter weight– Based on mature ORM technologies such as Hibernate & Toplink– Persistent entities can't be invoked remotely– Persistence can be used separately from other parts of EJB

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 31: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2120120715

Fast Track to EJB 3.1 and JPA 2

EJB 2.x Problems

Cumbersome and difficult to program– Each EJB required (at a minimum) an implementation class, a

home interface, a remote interface, and a deployment descriptor– The API was invasive – all the interfaces and classes were

directly tied to EJB specific types (via inheritance, implementing an interface, etc.)

– Client programs were also exposed to some of this complexity

Entity beans were not very useable– Some would say they were broken– The specification was also incomplete in terms of what was

required in terms of ORM, and how it was to be done– They were not used very much

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 32: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2220120715

Fast Track to EJB 3.1 and JPA 2

EJB 3.0 Goals

Simplify development– Annotations make programming simpler– Fewer classes required– API is simpler

Use POJOs and POJIs– Bean implementations can be POJO (Plain Old Java Objects)– Remote interfaces can be POJI (Plain Old Java Interfaces)– These are much easier to program– Reduces coupling to EJB specific types

Interceptor capability for session and message-driven beans

Remove need for home interfaces

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 33: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2320120715

Fast Track to EJB 3.1 and JPA 2

EJB 3.0 Goals

Make the most common usage easy– Defaults for most things, to reduce need for developer to specify

common, expected behaviors• e.g. – no empty ejbActivate() methods as in EJB 2.x

Resource and environmental dependencies easier– Dependency injection, annotations simplify programming

Support entity persistence well– Simpler API– Much more powerful capabilities, including support for

inheritance, polymorphism, relationships, embedded components– No required interfaces used - entities are POJOs

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 34: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2420120715

Fast Track to EJB 3.1 and JPA 2

EJB 3.1 Goals

Improve usability and functionality of EJB 3.0, including:

EJB without business interface (for local view)

Define portable global JNDI names for lookup

Add singleton session bean capability

Easy-to-use calendar-based timer service

Simple asynchronous session beans

EJB packaging within WAR files

EJB lite - subset of complete EJB capability

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 35: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2520120715

Fast Track to EJB 3.1 and JPA 2

Session Bean Usage

Session beans provide a number of useful capabilities

Transaction Management– Session beans provide easy access to the transaction service

available in EJB– Transactional behavior can be easily specified with annotations

in the bean class

Resource Management / Concurrent Access– EJB container manages bean instances, threads, memory issues– Very important for scalability in enterprise applications

Distributed Services / SOA– Session beans can be accessed remotely (directly via RMI)– Can also be used to implement Web Services

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 36: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2620120715

Fast Track to EJB 3.1 and JPA 2

Session Bean Usage

Fault Tolerance / Scalability– Most EJB containers support failover/high availability and some

form of load balancing / clustering

Security– Beans and individual methods in beans can be tied into the JEE

security system to secure access to them– Can be done by setting security attributes (in bean class via

annotations, or in XML DD)

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 37: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2720120715

Fast Track to EJB 3.1 and JPA 2

Persistent Entity Usage

ORM – Persistent entities are exclusively devoted to ORM– They model business data, and handle the interaction with the

database– You define a mapping from the bean class to the database, and

the framework generates all the JDBC code– Eliminates the need for complex, tedious, hand coded JDBC

Persistence available in Java SE - The persistence framework (javax.persistence) can be used independently– Does not need Java EE server– Can be used directly from Java SE (Standard Edition) program

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 38: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2820120715

Fast Track to EJB 3.1 and JPA 2

MDB Usage

Integrate EJB/server with messaging– Allows you to easily receive messages asynchronously on the

server side– Previous to MDB, there was no standard way to do this

Transaction Management– Allows you to easily start/control transactions when receiving

JMS messages– Can't be done directly for asynchronous message receiptwith the JMS API

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 39: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 2920120715

Fast Track to EJB 3.1 and JPA 2

Lab 1.1 – Setting Up the Environment

In this lab you will become familiar with and set up your application server and development

environment

Lab 1.1: Setting up the Environment

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 40: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 3020120715

Fast Track to EJB 3.1 and JPA 2

Review Questions

What is EJB?

What are the different kinds of beans defined in EJB, and what are they used for?

How is EJB 3 better than previous versions of EJB?

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 41: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 3120120715

Fast Track to EJB 3.1 and JPA 2

Lesson Summary

EJB is a framework for creating server-side components– Transactional, Distributed, Portable, Reliable, Secure, Scalable– It also defines a persistence API

EJB defines session beans, message-driven beans and persistent entities– Session beans provide distributed business services, and

access to container services such as transactions, concurrency control, etc.

– Message-driven beans receive JMS messages asynchronously, and integrate JMS with the EJB tier

– Persistent Entities provide an ORM framework to map between Java objects and relational data

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 42: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 3220120715

Fast Track to EJB 3.1 and JPA 2

Lesson Summary

EJB 3 simplifies and improves EJB in a number of ways– Uses Java annotations to eliminate/reduce the need for XML

deployment descriptors– Developers work with POJOs and POJIs rather than having to

derive from EJB specific interfaces and classes– The persistence technology has been completely rewritten based

on proven ORM technology– The persistence technology has been separated from the rest of

the specification and can be used independently

EJB 3.1 added more usability features and functionality– Singleton EJB, asynchronous EJB– Packaging EJB in a WAR– Portable JNDI names

Session 1: Introduction

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 43: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 30520120715

Fast Track to EJB 3.1 and JPA 2

Session 7: Introduction to the Java Persistence API (JPA 2)

JPA OverviewMapping a Simple Class

Entity Manager and Persistence ContextMore About Mappings

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 44: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 30620120715

Fast Track to EJB 3.1 and JPA 2

Lesson Objectives

Describe the issues of object-relational mapping

Describe the overall goals of the Java Persistence API Version 2 (JPA 2)

Describe the JPA architecture

Create a simple JPA application

Map a simple class to a DB using JPA

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 45: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 30720120715

Fast Track to EJB 3.1 and JPA 2

JPA Overview

JPA OverviewMapping a Simple Class

Entity Manager and Persistence ContextMore About Mappings

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 46: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 30820120715

Fast Track to EJB 3.1 and JPA 2

The Issues with Persistence Layers

Data - core element of many apps, often in relational DB

Much effort expended on persistence layers to store /retrieve this data– Complicated to write– "Homegrown" solutions often buggy and incomplete– DB schema changes often expensive to propagate to persistence

layer

OO languages (e.g. Java) complicate this more– Simple JDBC access has many issues:

• Low level SQL - not object based• To persist an object to the DB you write the SQL to do it• To load an object from the DB, write SQL, and get result rows from

the DB, which must usually be converted to objects hich must be converted into objects

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 47: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 30920120715

Fast Track to EJB 3.1 and JPA 2

Object-Relational Mapping (ORM) Issues

When using an OO language with a relational database, you are working with different models of using data– OO: Interacting objects traversed via relationships– Relational: Tables that are joined via foreign key relationships

These are very different models– Translating from one to the other requires work– There are many issues to deal with

Example, Inheritance: A core feature of OO models– Not supported in relational model

Relational Associations: only foreign key relationships– Object model: 1-1, 1-N, N-N

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 48: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31020120715

Fast Track to EJB 3.1 and JPA 2

Java Persistence API Overview

Completely new persistence framework for Java– Totally different from previous frameworks– Draws on technology from Hibernate, Toplink, JDO, and others– Replaces EJB Entity Beans

Overall goals– Provide ORM capability for using a Java OO domain model to

manage a relational database– Provide a light-weight POJO based framework for Java

persistence, including inheritance and polymorphism– Provide a query language (an extension of EJB QL) that helps

remove or encapsulate vendor specific SQL code– Relieve the developer from 95% of common data persistence

related programming tasks

JPA replaces the Entity bean technology in previous releases of EJB– Entity beans had significant problems in their architecture, and

they never caught on

There have been many ORM frameworks for Java available before JPA

– For example, Toplink, Hibernate, Kodo, and JDO

JPA provides a standard set of capabilities and a standard API for working with ORM

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 49: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31120120715

Fast Track to EJB 3.1 and JPA 2

JPA Benefits

Simplicity and flexibility– POJO based !– ORM is completely metadata driven (annotations or XML)– No need to write JDBC code – Common defaults that allow metadata to be minimized– Persistence API is totally separate from entity classes– Can be used in Java SE environments (without app server)

Completeness– Supports full range of OO features – Inheritance, custom object types, collections, associations– Powerful query language

Performance– Minimizes number of database updates– Lazy load on collections, disabling retrieval of associated objects– Object caching

JPA makes heavy use of defaults– The amount of metadata is minimized as much as possible– In some cases, almost no metadata will be needed

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 50: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31220120715

Fast Track to EJB 3.1 and JPA 2

Java Persistence Environments

Java Persistence introduced as standard part of JEE 5– JPA 2 part of JEE 6

Java Persistence can also be used in Java SE programs– It is packaged as a set of jar files– There are some minor configuration and programming

differences from using it in a Java EE environment– We'll show how to do it both ways

Application server support is widespread– Almost all application servers are supporting JPA– Most JPA support is built on top of a few existing technologies

• e.g. Oracle/Sun – Toplink based, Weblogic – Kodo based, JBoss –Hibernate based

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 51: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

JPA Architecture – High Level View

JPA uses database configuration data and entity metadata to provide persistence services and objects to the application– Generally, the JPA implementation is built over an existing

persistence provider, which in turn is built over JDBC

Database

Persistence Provider (e.g. Hibernate or TopLink)

JPA

Application

Mapped Entity Classes

JDBC

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31320120715

Fast Track to EJB 3.1 and JPA 2 Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 52: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

JPA Architecture – Programming View

There are a number of key types in using JPA– Persistence: For configuration of the system– EntityManager: Manages a set of persistent entities– EntityManagerFactory: Factory for EntityManagers– Query: For finding entities– Entity: POJO class mapped using JPA

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31420120715

Fast Track to EJB 3.1 and JPA 2 Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 53: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31520120715

Fast Track to EJB 3.1 and JPA 2

Mapping a Simple Class

JPA OverviewMapping a Simple Class

Entity Manager and Persistence ContextMore About Mappings

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 54: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31620120715

Fast Track to EJB 3.1 and JPA 2

Entity Classes

An entity is a lightweight persistent domain object– Entities are fine-grained objects representing state stored in a DB– An entity is one of the primary programming artifacts of JPA

Entities– Must be persistable – i.e. have a database representation– Have a persistent identity – basically the primary key in the DB– Are normally created/updated/deleted within a transaction

Entity metadata describes the mapping to the data store– Can be done with annotations (usually preferred) or XML– The metadata required is minimized through the use of intelligent

defaults– The core annotations are in the package javax.persistence

The concept of an entity has been present in database architecture for a long time

– An entity is basically a set of data that is grouped together– It may participate in relationships to other entities

In JPA any application defined object can be an entity

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 55: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31720120715

Fast Track to EJB 3.1 and JPA 2

Entity Class Requirements

Must be configured as an entity (via annotation or XML)

Implement a no argument constructor for JPA to instantiate instances (may have other constructors)

Contain instance variables to hold persistent state– Must NOT be declared public– Clients of the entity use accessor methods (get/set) for all

persistent fields

Provide an identifier property (usually called id)– Maps to primary key in database– Primitive type, or primitive wrapper, String, Date, composite key

If instances will be passed as a detached object (e.g. through a remote interface), it must implement Serializable

From the JPA 2 specification: – The entity class must be annotated with the Entity annotation or denoted in the XML descriptor– The no-arg constructor must be public or protected.– The entity class must be a top-level class. An enum or interface must not be designated as an

entity.– The entity class must not be final. No methods or persistent instance variables may be final.– If an entity instance is to be passed by value as a detached object (e.g., through a remote

interface), the entity class must implement the Serializable interface.– Entities support inheritance, polymorphic associations, and polymorphic queries.– Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well

as entity classes, and non-entity classes may extend entity classes.– The persistent state of an entity is represented by instance variables, which may correspond to

Java-Beans properties. An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself. Instance variables must not be accessed by clients of the entity. The state of the entity is available to clients only through the entity’s methods—i.e., accessor methods (getter/setter methods) or other business methods.

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 56: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31820120715

Fast Track to EJB 3.1 and JPA 2

An Example Entity Classpackage com.javatunes.schedule;

import java.sql.Date;import javax.persistence.Entity;import javax.persistence.Id;

@Entitypublic class Event implements java.io.Serializable {

@Idprivate Long id;private String title;private Date date;

Event() {}

public Event(Long id) { setId(id); }

public Long getId() { return id; }private void setId(Long id) { this.id = id; }

public Date getDate() { return date; }public void setDate(Date date) { this.date = date; }

public String getTitle() { return title; }public void setTitle(String title) { this.title = title; }

}

Regular classes can be transformed into entities by simply adding appropriate annotations– The class needs a no-arg constructor

You can also use an XML configuration file to declare that a class is an entity– In general, annotations are much more widely used, and will be used in this class

The persistent fields or properties of an entity may be of the following types: – Java primitive types and wrappers of the primitive types– java.lang.String; – java.math.BigInteger, java.math.BigDecimal

– java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp

– user-defined serializable types, – byte[], Byte[], char[], and Character[]);

– enums; – entity types and/or collections of entity types; – embeddable classes

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 57: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 31920120715

Fast Track to EJB 3.1 and JPA 2

javax.persistence.Entity Annotation

@Entity declares the class to be a persistent entityThe name of the entity defaults to the unqualified name of the class (Event)– This name is used in queries, which we cover later– The name can also be set with the name element of @Entity@Entity(name="OurEventEntity")

By default, it will be mapped to a table called Event– You can use @Table to declare a different table name– For example, if the table was called "EVENTS" you could use:

import javax.persistence.*;

@Entity@Table(name="EVENTS")public class Event { /* ... */ }

@Entity has only one element– name: The name of the entity for use in things like queries

The default table name is the Entity name– Which in our case is the default value of the unqualified name of the class– It can be changed using @Table(name="TableName")

@Table also has the following elements:– catalog: The catalog of the table– schema: The schema of the table– uniqueConstraints: Unique constraints to be placed on the table (used only if the table is

generated from the Entity class)– These are all only useful if you are generating the DDL (table definitions) from the JPA entities– It is in the javax.persistence package

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 58: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32020120715

Fast Track to EJB 3.1 and JPA 2

The Event Class

The event class has three properties– id (Long), date (java.sql.Date), title (String)– The id property holds a unique identifier for each event– Has JavaBean style get/set methods for all the properties– Also has no-argument constructor

By default, all non-transient properties are persistent– That is, they are stored in the database– By default, they are stored in a column with the same name as

the property– The column type in the database also uses reasonable defaults

Non-persistent properties can be annotated with @Transient– Fields that use the Java transient modifier are also not

persisted

JPA tries to use defaults that minimize the amount of metadata (annotation) information that is required in your entity classes

– If a property is present in your class, it is persistent according to the standard, basic defaults

– An optional @Basic annotation may be placed on the property to document this, but it's not necessary

Note that the setter for id is private in our class definition– Programs will not be allowed to change this value– This is a common way of defining the accessor methods for the

id

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 59: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32120120715

Fast Track to EJB 3.1 and JPA 2

javax.persistence.Id and ID property

@Id denotes that this property holds the primary key– A class must have a primary key– A non-composite primary key must correspond to a single field in

an entity (e.g. the id field in the Event class)

A simple primary key must be one of the following:– Java primitive or wrapper class (integral types most common)– java.lang.String, java.util.Date, java.sql.Date

Generated primary keys are supported– Only integral types will be portable

Composite primary keys are also possible– These use a primary key class

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties

– A primary key class must be defined to represent a composite primary key

– Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns

– @EmbeddedId and @IdClass are used to denote composite primary keys

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 60: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32220120715

Fast Track to EJB 3.1 and JPA 2

Field Access or Property Access

In the Event class, the persistence runtime will access the persistent fields directly in our event class– This is because we have annotated the persistent fields– It is also possible to annotate the accessor (getter/setter)

methods (see below)– In that case, the runtime will access the properties via the

accessor methods– This may be useful if you have business logic in the accessor

methods (e.g. validation logic)You should not mix field and accessor styles within a class– This is not portable

@Id // property access is usedpublic Long getId() { return id; }

Caution should be exercised in adding business logic to the accessor methods when property-based access is used. The order in which the persistence provider runtime calls these methods when loading or storing persistent state is not defined. Logic contained in such methods therefore cannot rely upon a specific invocation order. [JPA 2 Specification, Final, sec. 2.2]

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 61: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32320120715

Fast Track to EJB 3.1 and JPA 2

The EVENTS Table

Let's assume that the EVENTS table is declared as below

Assume you are using a generated primary key– A very common situation– The SQL shown is for the open source Derby database using an

Identity column

We'll look at how to map our Event class based on this table

CREATE TABLE EVENTS(

EVENT_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)

EVENT_DATE DATE,TITLE VARCHAR(80),CONSTRAINT PK_EVENTS PRIMARY KEY(EVENT_ID)

);

JPA has support for other types of generated values– For example, sequences and table generated keys

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 62: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32420120715

Fast Track to EJB 3.1 and JPA 2

Generated Id Property

You use @GeneratedValue to specify a generation strategy for primary keys– Possible strategies are:

• AUTO: Persistence provider picks best strategy for DB• IDENTITY: Uses DB identity column• SEQUENCE: Uses DB sequence column• TABLE: Uses underlying database table

You use @Column to specify the column nameBoth annotations are in javax.persistence

@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="EVENT_ID")private Long id;

@GeneratedValue also allows you to define a generator for the strategy@GeneratedValue(strategy=SEQUENCE, generator="EVENT_SEQ")

@Column has a large number of optional elements– For example: nullable, unique, …

@Column(name="SOME_COLUMN", nullable="false", unique=true)

– Some of these (e.g. nullable) are only used if you are generating the DDL from the entity declarations

– We'll cover some of them in the course– See the documentation for complete coverage

All these types are in the javax.persistence package

The AUTO strategy only makes sense if the runtime is generating the table definitions– Otherwise, of course, you'll need to use what's actually in the DB definition

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 63: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32520120715

Fast Track to EJB 3.1 and JPA 2

Mapping Properties

By default, all properties are considered persistent and mapped to columns with the same name as the property– However, all the defaults may not be appropriate for us– In our example, we map the date property to the EVENT_DATE column– The title property will map to the TITLE column by default, so we don't

need to do anything to change the defaults

// package / imports not shown in most examples ...

@Entitypublic class Event implements java.io.Serializable {

@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="EVENT_ID")private Long id;private String title;@Column(name="EVENT_DATE")private Date date;// Other code omitted ...

}

Notice that we've used a java.sql.Date in our class– That's because we designed it to be used with JPA

If you have a property that is a java.util.Date, or a java.util.Calendar, then JPA won't know how to map it

– Because it might be a date, a time, or a timestamp in the databaseFor java.util.Date and java.util.Calendar properties @Temporal must be used to specify how it is mapped to the database

– Here we specify it should be mapped as java.sql.Date@Temporal(TemporalType.DATE)

private java.util.Date someDate;

– The other values of TemporalType are:– TIME : Map as java.sql.Date– TIMESTAMP : Map as java.sql.Timestamp

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 64: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32620120715

Fast Track to EJB 3.1 and JPA 2

Basic Mapping Types

JPA can map a large number of persistable types– It automatically maps them to a JDBC type in the DB– If the type in the DB is different, it will do its best to convert it– The persistent fields or properties of an entity may be of the

following types: • Java primitive types and wrappers of the primitive types• java.lang.String; • java.math.BigInteger, java.math.BigDecimal• java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp

• byte[], Byte[], char[], and Character[]); • Enums; • User-defined serializable types, • Entity types and/or collections of entity types; • Embeddable classes

The simple types above are mapped as part of the immediate state of the entity

– They include almost all information that you want to persist

Sometimes the type in the database is not exactly the Java type– In almost all cases, the provider runtime can convert between the

two types– If the provider can't do the conversion, then generally an

exception will be thrown

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 65: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32720120715

Fast Track to EJB 3.1 and JPA 2

Temporal (Date/Time) Mappings

Temporal mappings can get somewhat complicated– There are multiple Java and database types, and the default

mappings between them are:– java.sql.Date: DATE– java.sql.TIME: TIME– java.sql.Timestamp: TIMESTAMP@Temporal is used to map java.util.Date and Calendarto the appropriate SQL type, as shown at bottom– These Java types are not specific enough for JPA to determine

the DB type, so @Temporal must be used– Can specify either DATE, TIME, or TIMESTAMP

@Temporal(TemporalType.DATE)

private Date date;

java.util.Date and java.util.Calendar do not supply enough information for JPA to map to the database

java.sql.Date will map to a DATE column by default– Our date property in MusicItem is of type java.util.Date, so we will need to use

@Temporal

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 66: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32820120715

Fast Track to EJB 3.1 and JPA 2

Persisting to the Database

An entity manager (abbreviated EM) is used to persist to the database– It is represented by the javax.persistence.EntityManager

interface – This interface encapsulates the API for persisting to the database– We'll look at this shortly

The entity manager API is completely separate from the mapping definition of an entity class– These responsibilities are not included in the mapping definition– This allows for a much cleaner definition of an entity class

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 67: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 32920120715

Fast Track to EJB 3.1 and JPA 2

Lab 7.1 – Mapping an Entity Class

In this lab we will map our MusicItem class to the database:

Lab 7.1 – Mapping an Entity Class

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 68: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33020120715

Fast Track to EJB 3.1 and JPA 2

Entity Manager and Persistence Context

JPA OverviewMapping a Simple Class

Entity Manager and Persistence ContextMore About Mappings

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 69: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33120120715

Fast Track to EJB 3.1 and JPA 2

The Persistence Unit

A persistence unit defines the set of entities that can be managed by an entity manager (covered next)– A persistence unit defines the types that can be managed, the

database they are persisted to, and the underlying mechanism used to persist entities (the persistence provider)

A persistence unit is named and configured in a configuration file (usually called persistence.xml)– It must be included in the META-INF directory of one of the jar

files in the application (called the root of the persistence unit)– It provides for standard JPA configuration

• Also allows provider specific configuration properties which arepassed through to the underlying provider

The persistence unit will be packaged up in a persistence archive– Basically just a jar that contains persistence.xml in the META-INF directory– The root jar file can be a regular jar, an ejb-jar, and others

The persistence unit is basically a configuration artifact that lets you specify things like how the DB is accessed, global configuration information such as transaction manager type, etc.

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 70: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33220120715

Fast Track to EJB 3.1 and JPA 2

persistence.xml

persistence.xml, as in the example below, defines a persistence unit– <persistence> specifies the namespaces and versions (JPA 2 )– <persistence-unit> defines the persistence unit– The required name attribute specifies the persistent unit name– The optional transaction-type attribute specifies transaction type– <jta-data-source> specifies the datasource JNDI lookup name

• JTAl (i.e. container transactions) used here – suitable for Java EE *– <properties> let you to pass configuration properties to the provider

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="…" version"2.0"> <!-- namespaces not shown --><persistence-unit name="events" transaction-type="JTA">

<jta-data-source>java:/EventDS</jta-data-source><properties><property name="hibernate.dialect"

value="org.hibernate.dialect.DerbyDialect"/></properties>

</persistence-unit></persistence>

The root <persistence> element specifies the namespaces and version according to the JPA spec– The labs and the example above are compatible with JPA 2– The labs include the complete namespace declarations which are not shown to save space

Different environments will use different transaction types– For example, in a Java SE environment, we would use JDBC transactions, and have transaction-

type="RESOURCE_LOCAL"Different underlying providers will require different configuration mechanism

– The property capability shown allows you to pass whatever properties the provider needs– These are dependent on the provider, and will vary for different providers

The hibernate.dialect property is a vendor specific property used to configure an underlying Hibernate provider

– It specifies the type of database that is being used– This allows Hibernate to optimize the SQL for that database

There are a number of other elements available in persistence.xml– See the documentation for more detail

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 71: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33320120715

Fast Track to EJB 3.1 and JPA 2

Classes included in a persistence unit

The classes included in a persistence unit are defined by:– Annotated managed persistence classes contained in the root of the

persistence unit (unless exclude-unlisted-classes is specified)– One or more object/relational mapping XML files– One or more jar files that will be searched for classes– An explicit list of classes

Generally, in a Java SE environment, you will use auto-scanning, where annotated persistent classes are automatically detected– The code sample below shows how to list them explicitly, if desired

(done in persistence.xml)

<!-- Disable scanning --><exclude-unlisted-classes>true</exclude-unlisted-classes><!-- Include the Event class --><class>com.javatunes.Event</class>

From the JPA spec [JPA 2 Specification, Final, Sec. 8.2.1.6]– All classes contained in the root of the persistence unit are searched for annotated managed persistence

classes—classes with the Entity, Embeddable, or MappedSuperclass annotation—and any mapping metadata annotations found on these classes will be processed, or they will be mapped using the mapping annotation defaults. If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element must be specified as true. The exclude-unlisted-classes element is not intended for use in Java SE environments.

– A object/relational mapping XML file named orm.xml [with mapping information for the classes listed in it] may be specified in the META-INF directory in the root of the persistence unit or in the META-INF directory of any jar file referenced by the persistence.xml. Alternatively, or in addition, one or more mapping files may be referenced by the mapping-file elements of the persistence-unit element. These mapping files may be present anywhere on the class path.

– An orm.xml mapping file or other mapping file is loaded as a resource by the persistence provider. If a mapping file is specified, the classes and mapping information specified in the mapping file will be used

– One or more JAR files may be specified using the jar-file elements instead of, or in addition to the mapping files specified in the mapping-file elements. If specified, these JAR files will be searched for managed persistence classes, and any mapping metadata annotations found on them will be processed, or they will be mapped using the mapping annotation defaults defined by this specification. Such JAR files are specified relative to the directory or jar file that contains[82] the root of the persistence unit.

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 72: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33420120715

Fast Track to EJB 3.1 and JPA 2

The EntityManager & Persistence Context

An entity manager (abbreviated EM) object is used to interact with a database, to create, read, or write an entity– An entity manager is configured to work with a specific data store– It also contains the API to interact with the data store

The EM also manages entity instances– When the EM obtains an entity reference, the referenced object

becomes a managed entity

A persistence context is associated with an EM, and is comprised of the set of all managed entities within it– Only one instance with a given persistent identity can exist

within a persistence context– e.g., if you get an event with id=25 twice from a persistent

context, the 2nd retrieval returns the same instance as the 1st

Entities don't interact with the database on their own, or contain the API to do so– Applications must use an entity manager to interact with the DB

Note that the idea of a persistence context is an important one– A persistence context is a set of entity instances in which for any persistent entity identity there is

a unique entity instance– Within a persistence context, database identity and Java identity are the same– Within a persistence context, the entity instances and their lifecycle are managed

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 73: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33520120715

Fast Track to EJB 3.1 and JPA 2

EntityManager Interface

EntityManager contains the entity manager API– Defines methods to create and remove persistent entities, to find

entities by their primary key, and to query over entities

Some important EntityManager methods include:– <T> T find(Class<T> entityClass, Object primaryKey):

Find an entity by its primary key– void persist(Object entity): Make a new entity instance

managed and persistent– void refresh(Object entity): Refresh the state of the

instance from the database, overwriting changes made to the entity, if any

– void remove(Object entity): Remove the entity instance

Many more methods – We'll cover many of them in the course

Note that an entity manager is not thread safe– It is meant to be used by a single thread at a time

Entities are also intended to be accessed by a single thread at a time while they are being managed– Really they also shouldn't be accessed by multiple threads when they are detached (which we

talk about later)– However, if you want to manage the thread safety in the entity instance for when it's detached,

it's possible to do so– It's not desirable– It's better to make copies and merge the state back into a persistence context

Notice that the find method is declared using Java generics– This allows you to use it without casting the return type– It's much more convenient than writing it in terms of Object and then casting the return value

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 74: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33620120715

Fast Track to EJB 3.1 and JPA 2

Obtaining an Entity Manager

An EntityManagerFactory provides EntityManagers– An EntityManagerFactory is bound to a persistence unit– It is thread-safe, and immutable

In Java SE, you usually programmatically create the entity manager with an entity manager factory– You also programmatically close it, and control the transactions

(either directly, or with another container like Spring)– We'll start with using JPA in a Java SE environment

In a Java EE or Spring environment, the entity manager is generally injected using dependency injection– Java EE also provides container managed transactions, and TX

scoped entity managers making JPA very easy to use– We'll look at this later

You can obtain an EntityManager from an EntityManagerFactory– Its behavior is controlled by the configuration properties– Any EntityManager you get from a given factory will only manage instances as defined by

that persistence unit

When you create and close an entity manager, you are also creating and destroying the associated persistence context

– This just means that when the entity manager is closed, all entities in the persistence context become unmanaged

– We'll look at this more when we talk about detached entities

When using EJB, you can also inject an entity manager by providing the name of the persistence unit– This is the preferred way to obtain an entity manager when working with EJB

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 75: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33720120715

Fast Track to EJB 3.1 and JPA 2

Injecting an EntityManager

An EntityManager is usually injected when used in an EJB– Using @PersistenceContext and the name of the persistence unit as

shown in the example below– The persistence unit is configured in persistence.xml– The EntityManager instance can only manage instances as defined by

the named persistence unit– The example uses a stateless session façade around the JPA code

// imports, etc. not shown ...@Statelesspublic class EventServiceBean implements EventService {@PersistenceContext(unitName="events")EntityManager em;

public void addEvent(Event event) {em.persist(event);

} // ...}

We're using an EventService EJB to encapsulate operations involving Event objects– This session bean façade is a common pattern– It hides the details of working with the EntityManager– It also hides details like the fact that the event id has to be extracted from the event after it is

persisted since the id is generated

In a Java SE environment, you generally use a bootstrap class called Persistence to read the configuration (persistence.xml)

– The Persistence type then produces the EntityManagerFactory, from which you can get EntityManagers

– You pass in the name of the persistence unit when creating the factory– You will likely use a resource-local entity manager

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 76: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33820120715

Fast Track to EJB 3.1 and JPA 2

Container-Managed Entity Manager

An entity manager obtained by injection is called a container-managed entity manager– When a container injects an entity manager, its persistence

context will be propagated within the current JTA transaction– Within the JTA transaction all EntityManager references that

are mapped to the same persistence unit will be associated with this same persistence context

– The lifetime of the persistence context is scoped to the lifetime of the JTA transaction

– Work is saved when the transaction ends– When the transaction ends, the persistence context is destroyed

This describes how a container-managed transaction-scoped entity manager works– There are other styles of operation (extended entity managers

and application-managed entity managers)

In Java EE environments, a JTA transaction typically involves calls across multiple components. Such components may often need to access the same persistence context within a single transaction. To facilitate such use of entity managers in Java EE environments, when an entity manager is injected into a component or looked up directly in JNDI its persistence context will automatically be propagated with the current JTA transaction, and the EntityManager references that are mapped to the same persistence unit will provide access to this same persistence context within the JTA transaction. This propagation of persistence context by the Java EE container avoids the need for the application to pass references to EntityManager instances from one component to another. An entity manager for which the container manages the persistence context in this manner is termed a container-managed entity manager. A container- managed entity manager’s lifecycle is managed by the Java EE container.

For a Java SE environment, where the application generally manages the entity manager, you can close an individual EntityManager instance by calling its close() method

– You can also close an EnityManagerFactory via its close() method– Closing the factory closes all its EntityManagers

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 77: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 33920120715

Fast Track to EJB 3.1 and JPA 2

Retrieving Persistent Objects

You can use the EntityManager.find() method to retrieve persistent objects from the database

– <T> T find(Class<T> entityClass, Object primaryKey)

– Returns the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

– If an instance with the given primary key is already associated with the persistence context, return that instance

// imports, etc. not shown ...@Statelesspublic class EventServiceBean {@PersistenceContext(unitName="events")EntityManager em;

public Event findById(Long id) {return em.find(Event.class,id);

} // ...}

The find method takes the class of the entity being sought, and the id or primary key that identifies the entity

– It returns a managed entity that is initialized with the data from the database

There is no cast required on the return value of the find method– It is defined using a parameterized return type, to return the same

type that was passed inIf there is no object found with the given id, then find returns a null

– No exception is thrown– Application code needs to check for nulls if this is a concern

There should only be one managed instance with a given primary key in a persistence context

– The methods of EntityManager that retrieve instances enforce this rule

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 78: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34020120715

Fast Track to EJB 3.1 and JPA 2

Lab 7.2 – Using an Entity Class

In this lab we will use the EntityManager to lookup MusicItem entities from data stored in a database

Lab 7.2 – Using an Entity Class

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 79: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34120120715

Fast Track to EJB 3.1 and JPA 2

More About Mappings

JPA OverviewMapping a Simple Class

Entity Manager and Persistence ContextMore About Mappings

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 80: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34220120715

Fast Track to EJB 3.1 and JPA 2

Default Mappings

JPA has defaults for many basic types, as summarized in the table– These types will by default be mapped to a database column with the

attribute name, and and can map to the database types shown below

The persistent fields and properties of an entity class are generically referred to in the JPA documentation as the “attributes” of the class

Note that a particular Java type may be mapped to a number of different database types– These are all supported by JPA, though there could conceivably be data loss depending on the

Java type and database type– For example, a string may be stored in a VARCHAR column that is not large enough for the

length of the string, and is truncated– If you use JPA to generate your DB schema, you can do things like specifying the length in the

column declaration

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 81: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34320120715

Fast Track to EJB 3.1 and JPA 2

@Basic and @Column

The default mapping is the equivalent of annotating an attribute with @Basic– It is applicable to any of the types in the previous slide– @Basic can also be used to change the fetch type (eager/lazy)– Generally it is not used when the defaults are fine@Column can be used to modify the mapping to the DB, and supports the following elements– name: Name of the column (default – attribute name)– table: Name of the table (if a secondary table – covered later)– insertable: Is column included in SQL inserts (default true)– updatable: Is column included in SQL updates (default true)– nullable: Can column hold null values (default true)– In addition, there are a number of attributes that are mainly

useful if JPA is used for table creation

@Column supports a number of elements that are generally only useful if JPA generates the database schema

– Providers have various tools to support this– The elements include the following:– length: The column length for strings (default 255)

• Typically only used during table creation, but some providers may actually validate the data during db operations

– precision: Precision of a numeric column – typically used in conjunction with scale– scale: Number of decimal digits a numeric column can hold

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 82: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34420120715

Fast Track to EJB 3.1 and JPA 2

Field and Property Access

The JPA runtime may access attributes directly, or through their property accessor (get) methods– Determined by where you put the access annotations– The example below annotated the get method – causing JPA to

access them using the accessor methods– Previously we annotated fields – resulting in direct field access– You must be consistent within a class – either annotating fields

or property methods– Alternatively, you can use @Access to explicitly declare the

access type (see notes)

@Entity // Most detail omittedpublic class Event implements java.io.Serializable {

@Idpublic Long getId() { return id; }private void setId(Long id) { this.id = id; }

}

@Access can be used to explicitly declare FIELD or PROPERTY (get/set) access for a type– You map the type with a particular access type– Individual attributes or properties can be designated to use the other access type by annotating

the instance variable or get method respectively using @Access– In the example below, all the attributes are accessed via field access, except for the date, which

uses property access– Generally this is not needed

@Entity // Most detail omitted

@Access(AccessType.FIELD)

public class Event implements java.io.Serializable {

@Access(AccessType.PROPERTY)

public Date getDate() { /*… */ }

public void setDate(Date dateIn) { /* … */ }

}

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 83: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34520120715

Fast Track to EJB 3.1 and JPA 2

Mapping Enums

Enum mapping is supported in two ways– By default, they are mapped using the enum integer values@Enumerated can be used to modify the mapping via specifying an EnumType of:– ORDINAL: Map as integer value of enum (the default)– STRING: Map as string value of enum– String values can be useful if people read the raw DB data

@Entity // Most detail omittedpublic class Event implements java.io.Serializable {

@ENUMERATED(EnumType.STRING) // Store in DB as string valueprivate EventType typeOfEvent;

}

public enum EventType { PUBLIC, PRIVATE}

Enums are typically used as constants

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 84: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34620120715

Fast Track to EJB 3.1 and JPA 2

Review Questions

Why do we need something like the Java Persistence API?

What does Java Persistence do?

What is an entity?

How do you map an entity to the database?

What is the id property of an entity?

What is a persistent context

What does the entity manager do?

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 85: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34720120715

Fast Track to EJB 3.1 and JPA 2

Lesson Summary

Object-relational mapping (ORM) is a difficult task– It takes a great deal of effort to write a persistence layers to store

and retrieve data from the database– The object and relational models have differences that add to

this difficulty

ORM tools automate this task for us– It allows you to define a mapping in some way, rather than write

code to implement that mapping

The Java Persistence API provides ORM capability for using a Java OO domain model to manage a relational database– POJO based, supporting inheritance and associations– Provides an object based query language

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 86: Table of Contents – EJB 3.1 and JPA 2 - ITCourseware · Types of Enterprise JavaBeans _____ 13 Java Persistence API ... EJB 3.0 Goals ...

Notes:

Copyright © 2006-12 LearningPatterns Inc. All rights reserved. 34820120715

Fast Track to EJB 3.1 and JPA 2

Lesson Summary

An entity is a lightweight persistent domain object– Metadata is used to describe the mapping to the database– Annotations are usually used, but XML files may also be used

Entities must had an id that uniquely identifies them– The ids may be auto-generated in the database– Sequences and identity rows are both supported

Entities are managed by an entity manager– A persistence context is comprised of the set of managed

entities within an entity manager– Only one instance with a given persistent identity can exist

within a persistence context– All interactions with the database are actually done using the

entity manager

Session 7: Introduction to the JPA

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.