Table of Contents EJB 3.1 and JPA 2

Similar documents
Fast Track to EJB 3.0 and the JPA Using JBoss

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Fast Track to EJB 3.0

"Charting the Course... Mastering EJB 3.0 Applications. Course Summary

Enterprise JavaBeans, Version 3 (EJB3) Programming

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Enterprise JavaBeans 3.1

JVA-163. Enterprise JavaBeans

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol

Java EE 7: Back-End Server Application Development

CO Java EE 7: Back-End Server Application Development

Developing Applications with Java EE 6 on WebLogic Server 12c

Module 8 The Java Persistence API

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Java EE 6: Develop Business Components with JMS & EJBs

Java Enterprise Edition

CO Java EE 6: Develop Database Applications with JPA

foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

Deccansoft Software Services. J2EE Syllabus

object/relational persistence What is persistence? 5

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics

Introduction to JPA. Fabio Falcinelli

V3 EJB Test One Pager

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

Web Application Development Using Spring, Hibernate and JPA

JPA Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

Web Application Development Using Spring, Hibernate and JPA

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

Web Application Development Using Spring, Hibernate and JPA

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand)

Fast Track to Java EE

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition

Oracle 10g: Build J2EE Applications

Implementing a Web Service p. 110 Implementing a Web Service Client p. 114 Summary p. 117 Introduction to Entity Beans p. 119 Persistence Concepts p.

Java EE Architecture, Part Three. Java EE architecture, part three 1(69)

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Deployment. See Packaging and deployment processes

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

New Features in EJB 3.1

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

Lightweight J2EE Framework

Developing Enterprise JavaBeans for Oracle WebLogic Server 12c (12.2.1)

POJOs to the rescue. Easier and faster development with POJOs and lightweight frameworks

Java SE7 Fundamentals

Chapter 6 Enterprise Java Beans

Java J Course Outline

Exam Questions 1Z0-895

Courses For Event Java Advanced Summer Training 2018

Topics in Enterprise Information Management

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline

Java SE 8 Fundamentals

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

JVA-563. Developing RESTful Services in Java

Business Component Development with EJB Technology, Java EE 5

DESIGN PATTERN - INTERVIEW QUESTIONS

JPA. Java persistence API

"Web Age Speaks!" Webinar Series

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14.

OracleAS 10g R3: Build J2EE Applications II

Java EE Architecture, Part Three. Java EE architecture, part three 1(57)

Erik Dörnenburg JAOO 2003

Architect Exam Guide. OCM EE 6 Enterprise. (Exams IZO-807,1ZO-865 & IZO-866) Oracle Press ORACLG. Paul R* Allen and Joseph J.

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product.

Java EE Architecture, Part Two. Java EE architecture, part two 1

OCP JavaEE 6 EJB Developer Study Notes

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Building the Enterprise

/ / JAVA TRAINING

Appendix A - Glossary(of OO software term s)

Using JNDI from J2EE components

Data Management in Application Servers. Dean Jacobs BEA Systems

POJOs in Action DEVELOPING ENTERPRISE APPLICATIONS WITH LIGHTWEIGHT FRAMEWORKS CHRIS RICHARDSON MANNING. Greenwich (74 w. long.)

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Dali Java Persistence Tools

Object-relational mapping EJB and Hibernate

Stateful Session Beans

Comparative Analysis of EJB3 and Spring Framework

ADVANCED JAVA TRAINING IN BANGALORE

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1

J2EE Interview Questions

SUN Sun Certified Enterprise Architect for J2EE 5. Download Full Version :

Spring Interview Questions

Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics:

Introduction to Session beans. EJB - continued

Migrating traditional Java EE applications to mobile

IBM. Enterprise Application Development with IBM Web Sphere Studio, V5.0

TOPLink for WebLogic. Whitepaper. The Challenge: The Solution:

What data persistence means? We manipulate data (represented as object state) that need to be stored

Index. setmaxresults() method, 169 sorting, 170 SQL DISTINCT query, 171 uniqueresult() method, 169

Apache OpenJPA User's Guide

Seam 3. Pete Muir JBoss, a Division of Red Hat

ΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ

JPA The New Enterprise Persistence Standard

SCBCD EXAM STUDY KIT. Paul Sanghera CX JAVA BUSINESS COMPONENT DEVELOPER CERTIFICATION FOR EJB MANNING. Covers all you need to pass

A COMPONENT BASED ONLINE ORDERING SYSTEM USING ENTERPRISE JAVABEANS 3.0

Transcription:

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved i

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved ii

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved iii

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved iv

@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 Copyright 2004-12 LearningPatterns Inc. All rights reserved v

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved vi

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved vii

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved viii

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved ix

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 Copyright 2004-12 LearningPatterns Inc. All rights reserved x

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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 1

Preface 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 2

Preface 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 3

Preface 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 4

Preface Course Prerequisites Proficiency in Java and Object-Oriented programming General knowledge of Java EE (Enterprise Edition) Knowledge of relational databases Copyright 2006-12 LearningPatterns Inc. All rights reserved. 5

Preface Labs Lab 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: STOP Copyright 2004-13 LearningPatterns Inc. All rights reserved. 6

Session 1: Introduction Session 1: Introduction Overview EJB 3.1 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 7

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 8

Session 1: Introduction Overview Overview EJB 3.1 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 9

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 10

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 11

Session 1: Introduction 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 a relational 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 12

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 13

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 14

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 15

Session 1: Introduction EJB in Java EE Architecture Web clients communicate via HTTP Rich clients can communicate via HTTP or RMI presentation business persistence client application server DB server browser HTTP client HTTP servlets JSPs Session EJB Persistent Entity database Swing GUI RMI This architecture may be attractive because you can support both Web 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 business tier. 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 16

Session 1: Introduction SOA and EJB SOA (Service Oriented Architecture) is an important basis for enterprise architectures Based 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 17

Session 1: Introduction SOA with Web Services and EJB Another popular Java EE architecture Provides loosely coupled access via standard protocols Web services business Java Client application server Web Services.NET Client SOAP/ HTTP SOAP/ HTTP Web Services Servlet EJB 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 18

Session 1: Introduction EJB 3 Overview EJB 3 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 19

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 20

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 21

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 22

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 23

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 24

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 25

Session 1: Introduction 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) Copyright 2006-12 LearningPatterns Inc. All rights reserved. 26

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 27

Session 1: Introduction 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 receipt with the JMS API Copyright 2006-12 LearningPatterns Inc. All rights reserved. 28

Lab 1.1: Setting up the Environment Lab 1.1 Setting Up the Environment In this lab you will become familiar with and set up your application server and development environment Copyright 2006-12 LearningPatterns Inc. All rights reserved. 29

Session 1: Introduction 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? Copyright 2006-12 LearningPatterns Inc. All rights reserved. 30

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 31

Session 1: Introduction 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 32

Session 7: Introduction to the JPA Session 7: Introduction to the Java Persistence API (JPA 2) JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright 2006-12 LearningPatterns Inc. All rights reserved. 305

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 306

Session 7: Introduction to the JPA JPA Overview JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright 2006-12 LearningPatterns Inc. All rights reserved. 307

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 308

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 309

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 310

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 311

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 312

Session 7: Introduction to the JPA 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 Application Mapped Entity Classes JPA Persistence Provider (e.g. Hibernate or TopLink) JDBC Database Copyright 2006-12 LearningPatterns Inc. All rights reserved. 313

Session 7: Introduction to the JPA 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. 314

Session 7: Introduction to the JPA Mapping a Simple Class JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright 2006-12 LearningPatterns Inc. All rights reserved. 315

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 316

Session 7: Introduction to the JPA 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. Copyright 2006-12 LearningPatterns Inc. All rights reserved. 317

Session 7: Introduction to the JPA An Example Entity Class package com.javatunes.schedule; import java.sql.date; import javax.persistence.entity; import javax.persistence.id; @Entity public class Event implements java.io.serializable { @Id private 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 318

Session 7: Introduction to the JPA javax.persistence.entity Annotation @Entity declares the class to be a persistent entity The 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 319

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 320

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 321

Session 7: Introduction to the JPA 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 used public 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] Copyright 2006-12 LearningPatterns Inc. All rights reserved. 322

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 323

Session 7: Introduction to the JPA 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 name Both 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 324

Session 7: Introduction to the JPA 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... @Entity public 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 database For 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 325

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 326

Session 7: Introduction to the JPA 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 Calendar to 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 327

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 328

Lab 7.1 Mapping an Entity Class Lab 7.1 Mapping an Entity Class In this lab we will map our MusicItem class to the database: Copyright 2006-12 LearningPatterns Inc. All rights reserved. 329

Session 7: Introduction to the JPA Entity Manager and Persistence Context JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright 2006-12 LearningPatterns Inc. All rights reserved. 330

Session 7: Introduction to the JPA 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 are passed 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. Copyright 2006-12 LearningPatterns Inc. All rights reserved. 331

Session 7: Introduction to the JPA 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 transactiontype="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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 332

Session 7: Introduction to the JPA 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. Copyright 2006-12 LearningPatterns Inc. All rights reserved. 333

Session 7: Introduction to the JPA 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 2 nd retrieval returns the same instance as the 1 st 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 334

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 335

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 336

Session 7: Introduction to the JPA 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... @Stateless public 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 337

Session 7: Introduction to the JPA Container-Managed Entity Manager An entity manager obtained by injection is called a containermanaged 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 transactionscoped 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 338

Session 7: Introduction to the JPA 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... @Stateless public 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 in If 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 339

Lab 7.2 Using an Entity Class 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 340

Session 7: Introduction to the JPA More About Mappings JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright 2006-12 LearningPatterns Inc. All rights reserved. 341

Session 7: Introduction to the JPA 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 Copyright 2006-12 LearningPatterns Inc. All rights reserved. 342