Fast Track to EJB 3.0

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

Table of Contents EJB 3.1 and JPA 2

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

Enterprise JavaBeans, Version 3 (EJB3) Programming

JVA-163. Enterprise JavaBeans

CO Java EE 7: Back-End Server Application Development

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

Java Enterprise Edition

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

Java EE 6: Develop Business Components with JMS & EJBs

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

Java EE 7: Back-End Server Application Development

NetBeans IDE Field Guide

Deccansoft Software Services. J2EE Syllabus

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

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

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

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

Enterprise JavaBeans 3.1

Developing Applications with Java EE 6 on WebLogic Server 12c

V3 EJB Test One Pager

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

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

Oracle 10g: Build J2EE Applications

Fast Track to Java EE

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

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8

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

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

CO Java EE 6: Develop Database Applications with JPA

Exam Questions 1Z0-895

Course: JBoss Training: JBoss AS 7 and JBoss EAP 6 Administration and Clustering Training

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

Web Application Development Using Spring, Hibernate and JPA

Fast Track to Spring 3 and Spring Web Flow 2.1

WA2031 WebSphere Application Server 8.0 Administration on Windows. Student Labs. Web Age Solutions Inc. Copyright 2012 Web Age Solutions Inc.

Chapter 6 Enterprise Java Beans

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 Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Business Component Development with EJB Technology, Java EE 5

OracleAS 10g R3: Build J2EE Applications II

New Features in EJB 3.1

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

JBOSS AS 7 AND JBOSS EAP 6 ADMINISTRATION AND CLUSTERING (4 Days)

Fast Track. Evaluation Copy. to Spring 3.x. on Eclipse/Tomcat. LearningPatterns, Inc. Courseware. Student Guide

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

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

Web Application Development Using Spring, Hibernate and JPA

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

In the most general sense, a server is a program that provides information

JVA-563. Developing RESTful Services in Java

Web Application Development Using Spring, Hibernate and JPA

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

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

IBM Workplace Collaboration Services API Toolkit

Java J Course Outline

object/relational persistence What is persistence? 5

J2EE Interview Questions

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

/ / JAVA TRAINING

Enterprise JavaBeans. Layer:01. Overview

Overview p. 1 Server-side Component Architectures p. 3 The Need for a Server-Side Component Architecture p. 4 Server-Side Component Architecture

Web Design and Applications

Table of Contents - Fast Track to Hibernate 3

Oracle Application Development Framework Overview

Appendix A - Glossary(of OO software term s)

Java Programming Language

ActiveSpaces Transactions. Quick Start Guide. Software Release Published May 25, 2015

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

Oracle WebLogic Server 11g: Administration Essentials

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

Administering the JBoss 5.x Application Server

BEAAquaLogic. Service Bus. Interoperability With EJB Transport

OCP JavaEE 6 EJB Developer Study Notes

Comparative Analysis of EJB3 and Spring Framework

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

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

Building the Enterprise

"Web Age Speaks!" Webinar Series

Rational Application Developer 7 Bootcamp

Deployment. See Packaging and deployment processes

Chapter 2 Introduction

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

CERTIFICATION SUCCESS GUIDE ENTERPRISE ARCHITECT FOR JAVA 2 PLATFORM, ENTERPRISE EDITION (J2EE ) TECHNOLOGY

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

Table of Contents Fast Track to Java EE 5 with Servlets/JSP and JDBC

EVALUATION ONLY. WA2097 WebSphere Application Server 8.5 Administration on Linux. Student Labs. Web Age Solutions Inc.

Mastering BEA WebLogic Server Best Practices for Building and Deploying J2EE Applications

Skyway Builder 6.3 Reference

133 July 23, :01 pm

BEAWebLogic Server. Introduction to BEA WebLogic Server and BEA WebLogic Express

"Charting the Course... Java Programming Language. Course Summary

Data Management in Application Servers. Dean Jacobs BEA Systems

Courses For Event Java Advanced Summer Training 2018

JBoss SOAP Web Services User Guide. Version: M5

Teamcenter Global Services Customization Guide. Publication Number PLM00091 J

LearningPatterns, Inc. Courseware Student Guide

PASS4TEST. IT Certification Guaranteed, The Easy Way! We offer free update service for one year

Transcription:

Fast Track to EJB 3.0 using JBoss 4/5 and Eclipse LearningPatterns, Inc. Courseware JBoss is a registered trademark of Red Hat, Inc. in the U.S. and other countries. LearningPatterns has no affiliation with Red Hat. LearningPatterns is a trademark of LearningPatterns Inc. Student Guide

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright 2004-8 LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. Global Courseware Services Services@learningpatterns.com www.learningpatterns.com 55 Wanaque Ave. #188 Pompton Lakes, NJ 07442 USA 212.487.9064 voice 201.336.9118 fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Sun Microsystems, Inc., in the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns Inc. All other products referenced herein are trademarks of their respective holders.

Table of Contents - Fast Track to EJB3 ENTERPRISE JAVABEANS V3.0... 1 WORKSHOP OVERVIEW... 2 WORKSHOP OBJECTIVES... 3 WORKSHOP AGENDA... 4 COURSE PREREQUISITES... 5 RELEASE LEVEL... 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.0... 19 EJB 3.0 OVERVIEW... 20 EJB 2.X PROBLEMS... 21 EJB 3.0 GOALS... 22 EJB 3.0 GOALS... 23 SESSION BEAN USAGE... 24 SESSION BEAN USAGE... 25 PERSISTENT ENTITY USAGE... 26 MDB USAGE... 27 LAB 1.1 SETTING UP THE ENVIRONMENT... 28 REVIEW QUESTIONS... 44 LESSON SUMMARY... 45 SESSION 2: SESSION BEANS... 47 LESSON OBJECTIVES... 48 SESSION BEAN OVERVIEW... 49 WHAT ARE SESSION BEANS... 50 STATELESS SESSION BEANS (SLSB)... 51 STATEFUL SESSION BEANS (SFSB)... 52 SESSION BEANS CAN BE DISTRIBUTED... 53 DEFINING A SESSION BEAN... 54 STATELESS SESSION BEAN DEFINITION... 55 CALCULATOR REMOTE BUSINESS INTERFACE... 56 REMOTE AND LOCAL BUSINESS INTERFACES... 57 CALCULATOR BEAN LOCAL BUSINESS INTERFACE... 58 A BRIEF NOTE ON ANNOTATIONS... 59 HOW ANNOTATIONS WORK... 60 ANNOTATION DEFINITION... 61 USING ANNOTATIONS... 62 Copyright 2006-8, LearningPatterns Inc. All rights reserved i

WHAT ELSE IS NEEDED... 63 PACKAGING AND DEPLOYMENT... 64 J2EE PACKAGING... 65 EJB-JAR FILE... 66 DEPLOYMENT DESCRIPTOR (DD)... 67 DEPLOYMENT DESCRIPTORS IN EJB 3... 68 EJB-JAR FILE STRUCTURE... 69 ENTERPRISE ARCHIVE (EAR FILE)... 70 APPLICATION.XML FILE... 71 SERVER DEPLOYMENT... 72 EJB CONTAINER... 73 THE EJB CONTAINER...74 SERVER DEPLOYMENT... 75 LAB 2.1 WRITE AND DEPLOY AN EJB... 76 JNDI OVERVIEW... 91 HOW DO REMOTE CLIENTS GET EJB ACCESS... 92 JNDI JAVA NAMING AND DIRECTORY INTERFACE... 93 EJB CONTAINER BINDS A REFERENCE INTO JNDI... 94 CLIENT LOOKS UP REFERENCE IN JNDI... 95 JNDI TREE STRUCTURE... 96 JNDI TREE STRUCTURE... 97 JNDI API OVERVIEW...98 JNDI API... 99 THE CONTEXT INTERFACE... 100 THE INITIALCONTEXT CLASS... 101 SPECIFYING THE INITIALCONTEXT PROPERTIES... 102 USING JNDI... 103 EJB CLIENT... 104 CLIENT VIEW OF A SESSION BEAN... 105 CLIENT INVOCATION OF A SESSION EJB... 106 PORTABLEREMOTEOBJECT AND CASTING... 107 RUNNING A CLIENT... 108 LAB 2.2 WRITE AND RUN AN EJB CLIENT... 109 REVIEW QUESTIONS...118 LESSON SUMMARY... 119 SESSION 3: ADDITIONAL EJB CAPABILITIES... 121 LESSON OBJECTIVES... 122 DEPENDENCY INJECTION... 123 DEPENDENCY INJECTION... 124 THE JAVATUNES ONLINE MUSIC STORE... 125 AN EJB REFERENCING ANOTHER EJB... 126 CATALOGMAINTENANCE... 127 INJECTION OF CATALOGMAINTENANCE... 128 WHAT IS HAPPENING... 129 LAB 3.1 DEPENDENCY INJECTION... 130 DEPLOYMENT DESCRIPTORS...146 MORE ABOUT DEPLOYMENT DESCRIPTORS... 147 THE XML DEPLOYMENT DESCRIPTOR... 148 SAMPLE STANDARD DEPLOYMENT DESCRIPTOR... 149 Copyright 2006-8, LearningPatterns Inc. All rights reserved ii

THE EJB ENVIRONMENT... 150 ISSUES WITH OBTAINING RESOURCES... 151 REFERENCING RESOURCES EXTERNAL TO EAR... 152 REFERENCES & DEPLOYMENT DESCRIPTOR USAGE... 153 RESOLVING A JNDI NAME... 154 RESOLVING A JNDI NAME... 155 SIMPLE ENVIRONMENT ENTRIES... 156 SIMPLE ENVIRONMENT ENTRY EXAMPLE... 157 DECLARING SIMPLE ENVIRONMENT ENTRIES... 158 SETTER INJECTION... 159 RESOURCE MANAGER CONNECTION FACTORIES... 160 RESOURCE MANAGER CONNECTION FACTORIES... 161 DATASOURCE REFERENCE EXAMPLE - BEAN... 162 DATASOURCE REFERENCE EXAMPLE - DD... 163 MORE ON THE ENTERPRISE BEAN ENVIRONMENT... 164 THE ENVIRONMENT IS A LEVEL OF INDIRECTION... 165 LOOKING UP RESOURCES IN THE ENVIRONMENT... 166 LOOKING UP VIA EJBCONTEXT... 167 LOOKING UP VIA JNDI API... 168 MORE ON THE @STATELESS ANNOTATION... 169 @STATELESS EXAMPLE... 170 MORE ON THE @EJB ANNOTATION... 171 MORE ON THE @RESOURCE ANNOTATION... 172 DEPLOYMENT DESCRIPTOR VS ANNOTATION... 173 LAB 3.2 SIMPLE ENVIRONMENT ENTRY... 174 STATELESS SESSION BEAN LIFECYCLE & INTERCEPTORS... 178 OVERVIEW... 179 STATELESS SESSION BEAN STATE DIAGRAM... 180 LIFE CYCLE OF SSB... 181 CLIENT CALL OF A STATELESS SB METHOD... 182 INTERCEPTORS... 183 BUSINESS METHOD INTERCEPTORS... 184 BUSINESS METHOD INTERCEPTORS EXAMPLE... 185 INVOCATIONCONTEXT INTERFACE DETAILS... 186 INTERCEPTOR METHOD DETAILS... 187 INTERCEPTOR CLASS... 188 USING INTERCEPTOR CLASSES... 189 METHOD LEVEL INTERCEPTORS... 190 LIFECYCLE CALLBACK INTERCEPTORS... 191 LIFECYCLE INTERCEPTOR IN THE BEAN CLASS... 192 LIFECYCLE INTERCEPTOR IN A SEPARATE CLASS... 193 LAB 3.3 INTERCEPTORS... 194 STATEFUL SESSION BEANS... 198 STATEFUL SESSION BEAN (SFSB) OVERVIEW... 199 CODING A STATEFUL SESSION BEAN... 200 STATEFUL SESSION BEAN CLIENTS... 201 STATEFUL SESSION BEAN REMOVAL... 202 STATEFUL SESSION PASSIVATION/ACTIVATION... 203 WHEN TO USE STATEFUL SESSION BEANS... 204 @PREPASSIVATE AND @POSTACTIVATE CALLBACKS... 205 STATEFUL SESSION BEAN STATE DIAGRAM... 206 LAB 3.4 STATEFUL SESSION BEANS... 207 THE TIMER SERVICE... 215 Copyright 2006-8, LearningPatterns Inc. All rights reserved iii

OVERVIEW... 216 BEAN REQUIREMENTS... 217 THE JAVAX.EJB.TIMER INTERFACE... 218 THE JAVAX.EJB.TIMERSERVICE INTERFACE... 219 TIMER EXAMPLE... 220 HOW THE TIMER WORKS... 221 ISSUES WITH USING THE TIMER SERVICE... 222 REVIEW QUESTIONS...223 LESSON SUMMARY... 224 LESSON SUMMARY... 225 SESSION 4: MESSAGE-DRIVEN BEANS... 226 LESSON OBJECTIVES... 227 OVERVIEW OF MESSAGING SYSTEMS... 228 WHAT IS MESSAGING?... 229 LOOSE COUPLING... 230 WHEN IS MESSAGING USED?... 231 TWO MESSAGING MODELS... 232 PUBLISH/SUBSCRIBE - ILLUSTRATED... 233 MORE ON PUBLISH/SUBSCRIBE... 234 POINT-TO-POINT - ILLUSTRATED... 235 MORE ON POINT-TO-POINT (P2P)... 236 MESSAGE DELIVERY - PUSH VERSUS PULL... 237 OVERVIEW OF JMS API... 238 WHAT IS JAVA MESSAGE SERVICE?... 239 API STRUCTURE... 240 JMS INTERFACES... 241 ADMINISTERED OBJECTS... 242 ADMINISTERED OBJECTS AND JNDI - ILLUSTRATED... 243 CLIENT WORKFLOW...244 QUEUE PRODUCER CLIENT EXAMPLE... 245 QUEUE PRODUCER CLIENT EXAMPLE... 246 SYNCHRONOUS QUEUE CONSUMER CLIENT... 247 ASYNCHRONOUS QUEUE CONSUMER CLIENT... 248 MESSAGE LISTENER EXAMPLE... 249 JMS MESSAGE TYPES... 250 MESSAGE HEADER FIELDS... 251 MESSAGE-DRIVEN BEANS... 252 J2EE MESSAGE PRODUCERS AND CONSUMERS... 253 MESSAGE-DRIVEN BEAN (MDB) OVERVIEW... 254 GOALS OF MESSAGE-DRIVEN BEANS... 255 SIMPLE MDB EXAMPLE... 256 MDB CONSUMPTION OF A MESSAGE... 257 @MESSAGEDRIVEN DETAILS... 258 ACTIVATION CONFIGURATION PROPERTIES... 259 SPECIFYING A DESTINATION FOR AN MDB... 260 SPECIFYING A DESTINATION USING A DD... 261 MESSAGE-DRIVEN BEAN LIFECYCLE... 262 LIFECYCLE OVERVIEW... 263 MDB STATE DIAGRAM... 264 INTERCEPTOR METHODS... 265 LAB 4.1 MESSAGE DRIVEN BEAN... 266 Copyright 2006-8, LearningPatterns Inc. All rights reserved iv

REVIEW QUESTIONS...276 LESSON SUMMARY... 277 SESSION 5: TRANSACTIONS AND SECURITY... 278 LESSON OBJECTIVES... 279 TRANSACTION DEFINITION... 280 TRANSACTION OVERVIEW... 281 TRANSACTION LIFECYCLE... 282 TRANSACTIONS CLARIFY SYSTEMS... 283 TRANSACTIONAL SYSTEM OVERVIEW... 284 OVERVIEW OF A TRANSACTIONAL SYSTEM... 285 TRANSACTIONAL SYSTEM COMPONENTS... 286 TRANSACTIONAL SYSTEM COMPONENTS... 287 TRANSACTIONAL OBJECT... 288 EJB TRANSACTION SUPPORT... 289 TRANSACTIONS IN EJB... 290 EJB DECLARATIVE TRANSACTION MANAGEMENT... 291 TRANSACTIONAL SCOPE... 292 EJB TRANSACTION ATTRIBUTES... 293 SPECIFYING TRANSACTION ATTRIBUTES... 294 SPECIFYING TRANSACTION ATTRIBUTES... 295 NOTSUPPORTED... 296 SUPPORTS... 297 REQUIRED... 298 REQUIRESNEW... 299 MANDATORY... 300 NEVER... 301 BEANS HAVE A SAY IN TRANSACTIONS... 302 BEANS CAN BE NOTIFIED OF TRANSACTION STATUS... 303 TRANSACTION EXAMPLE... 304 TRANSACTION ATTRIBUTES SOME CHOICES... 305 TRANSACTION ATTRIBUTES - SOME CHOICES... 306 EXPLICIT / BEAN-MANAGED TRANSACTIONS... 307 USERTRANSACTION & BEAN-MANAGED EXAMPLE... 308 TRANSACTION ISOLATION LEVELS... 309 TRANSACTION ISOLATION LEVELS USAGE... 310 MULTI-PROCESS TX AND TWO PHASE COMMIT... 311 LAB 5.1 TRANSACTIONS... 312 SECURITY IN EJB... 318 SECURITY REQUIREMENTS... 319 J2EE SECURITY... 320 ROLES... 321 J2EE SECURITY OVERVIEW... 322 EJB SECURITY OVERVIEW... 323 ANNOTATION EXAMPLE... 324 EXAMPLE: ROLES AND METHOD PERMISSIONS... 325 ANNOTATION EXAMPLE... 326 SAME EXAMPLE WITH ANNOTATIONS... 327 AUTHENTICATION... 328 PROGRAMMATIC SECURITY... 329 EXAMPLE OF PROGRAMMATIC SECURITY... 330 TRANSPORT LEVEL SECURITY WITH SSL... 331 Copyright 2006-8, LearningPatterns Inc. All rights reserved v

LAB 5.2 SECURITY... 332 REVIEW QUESTIONS...342 LESSON SUMMARY... 343 SESSION 6: EXCEPTION HANDLING AND BEST PRACTICES... 345 LESSON OBJECTIVES... 346 EXCEPTION HANDLING... 347 OVERVIEW OF EXCEPTIONS... 348 EXCEPTION HIERARCHY... 349 APPLICATION EXCEPTIONS IN EJB... 350 DEFINING APPLICATION EXCEPTIONS... 351 APPLICATION EXCEPTION EXAMPLE... 352 CONTAINER HANDLING OF APPLICATION EXCEPTION... 353 BEAN THROWING OF APPLICATION EXCEPTION... 354 CLIENT HANDLING OF APPLICATION EXCEPTIONS... 355 SYSTEM EXCEPTIONS INDICATE FAILURE... 356 CONTAINER HANDLING OF SYSTEM EXCEPTION... 357 CLIENT HANDLING OF SYSTEM EXCEPTIONS... 358 EJB 3 BEST PRACTICES... 359 WHEN TO USE EJB... 360 KEEP BUSINESS INTERFACES COARSE GRAINED... 361 SESSION FAÇADE STRUCTURE... 362 USE CONTAINER-MANAGED TRANSACTIONS... 363 TRANSACTION DURATION... 364 LOCAL AND REMOTE BUSINESS INTERFACE... 365 TUNING... 366 SESSION BEAN TUNING... 367 CLUSTERING... 368 CLUSTERING SESSION BEANS... 369 REVIEW QUESTIONS...370 LESSON SUMMARY... 371 LESSON SUMMARY... 372 SESSION 7: INTRODUCTION TO THE JAVA PERSISTENCE API (JPA)... 373 LESSON OBJECTIVES... 374 JPA OVERVIEW... 375 THE ISSUES WITH PERSISTENCE LAYERS... 376 OBJECT-RELATIONAL MAPPING (ORM) ISSUES... 377 ISSUES WITH JDBC ALONE... 378 JAVA PERSISTENCE API OVERVIEW... 379 JPA BENEFITS... 380 JAVA PERSISTENCE ENVIRONMENTS... 381 MAPPING A SIMPLE CLASS... 382 ENTITY CLASSES... 383 ENTITY CLASS REQUIREMENTS... 384 AN EXAMPLE ENTITY CLASS... 385 THE ENTITY DECLARATION... 386 THE EVENT CLASS... 387 THE ID PROPERTY... 388 FIELD ACCESS OR PROPERTY ACCESS... 389 THE EVENTS TABLE... 390 GENERATED ID PROPERTY... 391 Copyright 2006-8, LearningPatterns Inc. All rights reserved vi

MAPPING PROPERTIES... 392 BASIC MAPPING TYPES... 393 PERSISTING TO THE DATABASE... 394 LAB 7.1 MAPPING AN ENTITY CLASS... 395 ENTITY MANAGER AND PERSISTENCE CONTEXT... 401 THE ENTITY MANAGER & PERSISTENCE CONTEXT... 402 THE ENTITYMANAGER... 403 THE ENTITYMANAGER INTERFACE... 404 PERSISTENCE UNIT... 405 INJECTING AN ENTITYMANAGER... 406 RETRIEVING PERSISTENT OBJECTS... 407 CONTAINER-MANAGED ENTITY MANGER... 408 THE PERSISTENCE UNIT... 409 PERSISTENCE.XML... 410 LAB 7.2 USING AN ENTITY CLASS... 411 REVIEW QUESTIONS...420 LESSON SUMMARY... 421 SESSION 8: UPDATES AND QUERIES... 423 LESSON OBJECTIVES... 424 INSERTING AND UPDATING... 425 TRANSIENT, PERSISTENT, DETACHED INSTANCES... 426 REMOVED INSTANCES... 427 PERSISTING A NEW ENTITY... 428 PERSISTING A NEW ENTITY EXAMPLE... 429 SYNCHRONIZATION TO THE DATABASE... 430 UPDATING A PERSISTENT INSTANCE... 431 LAB 8.1 INSERTING AND UPDATING... 432 QUERYING AND JAVA PERSISTENCE QUERY LANGUAGE (JPQL)... 437 JAVA PERSISTENCE QUERY LANGUAGE... 438 EXECUTING A QUERY... 439 EXECUTING A QUERY... 440 WHERE CLAUSE... 441 QUERY PARAMETERS... 442 USING QUERY PARAMETERS... 443 NAMED QUERIES... 444 NAMED QUERIES... 445 LAB 8.2 BASIC QUERYING... 446 REVIEW QUESTIONS...450 LESSON SUMMARY... 451 [OPTIONAL] SESSION 9: ENTITY RELATIONSHIPS... 453 LESSON OBJECTIVES... 454 MAPPING RELATIONSHIPS... 455 OBJECT RELATIONSHIPS... 456 MAPPINGS OVERVIEW... 457 UNIDIRECTIONAL MANY-TO-ONE RELATIONSHIP... 458 THE TABLE STRUCTURE MANY-TO-ONE... 459 THE OWNING SIDE... 460 @JOINCOLUMN... 461 BIDIRECTIONAL ONE-TO-MANY RELATIONSHIP... 462 MAPPING THE ONE-TO-MANY RELATIONSHIP... 463 Copyright 2006-8, LearningPatterns Inc. All rights reserved vii

USING THE RELATIONSHIP... 464 MORE ON THE INVERSE SIDE... 465 OTHER TYPES OF RELATIONSHIPS... 466 LAZY AND EAGER LOADING... 467 CASCADING OPERATIONS... 468 QUERIES ACROSS RELATIONSHIPS... 469 MAPPING INHERITANCE... 470 ENTITY INHERITANCE... 471 DETAILS OF ENTITY INHERITANCE... 472 JOINED (TABLE PER SUBCLASS)... 473 ENTITY DEFINITIONS FOR JOINED... 474 JOINED: PROS AND CONS... 475 SINGLE TABLE MAPPING STRATEGY... 476 TABLE PER CONCRETE CLASS... 477 REVIEW QUESTIONS...478 REVIEW QUESTIONS...479 LESSON SUMMARY... 480 [OPTIONAL] SESSION 10: ADDITIONAL JAVA PERSISTENCE CAPABILITIES... 483 LESSON OBJECTIVES... 484 VERSIONING... 485 OPTIMISTIC LOCKING / DETACHED INSTANCES... 486 VERSIONING... 487 MORE ON QUERYING... 488 PROJECTION QUERIES... 489 AGGREGATE QUERIES... 490 BULK UPDATE AND DELETE... 491 NATIVE SQL QUERIES... 492 EMBEDDED OBJECTS... 493 USING EMBEDDED OBJECTS... 494 EMBEDDABLE CLASS... 495 JAVA PERSISTENCE WITH JAVA SE... 496 USING JPA WITH JAVA SE... 497 JAVA SE APIS... 498 EXAMPLE OF JPA IN JAVA SE... 499 RESOURCES (EJB3 AND JPA)... 500 RESOURCES... 501 END OF SESSION... 502 Copyright 2006-8, LearningPatterns Inc. All rights reserved viii

Enterprise JavaBeans V3.0 The Java Developer Education Series LearningPatterns Inc. Java, EJB, Enterprise JavaBeans and all Java-based trademarks are registered trademarks of Sun Microsystems, Inc Copyright 2006-9 LearningPatterns Inc. All rights reserved. 1

Preface Workshop Overview This is a three hands-on course providing a thorough introduction to Enterprise JavaBeans V3.0, including The needs EJB is designed to address The basic concepts and architecture Thorough coverage of the EJB API and details on its use An introduction to the Java Persistence API (JPA) Design principles for correct usage The workshop consists of 50% discussion, 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-9 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/J2EE Understand EJB concepts and architecture Be familiar with the EJB API, including the Java Persistence API (JPA) Be able to write and use EJBs, both Session Beans and Message Driven Beans Be familiar with the JPA API, and be able to write and use persistent entities Understand the tradeoffs involving EJB Understand important design principles for EJB Copyright 2006-9 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 (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-9 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-9 LearningPatterns Inc. All rights reserved. 5

Preface Release Level Lab This course contains instructions for running the EJB 3 labs using the following platforms: Java 5 (Java Development Kit 1.5.0_xx) Java 5 is required since EJB 3 depends on Java 5 annotations JBoss 4.2.x.GA or JBoss 5.0.x.GA Eclipse 3.4 Java EE Edition (Ganymede) All labs have been tested on Microsoft Windows XP, Java 5, JBoss 4.2.2.GA and JBoss 5.0.1.GA JBoss is a registered trademarks of Red Hat, Inc in the U.S. and other countries. LearningPatterns is not in any way associated with Red Hat or its JBoss Division. It is likely that using Java-6 will work without problems However, we have not tested it using Java 6 Note that JBoss 5 has separate downloads for running under Java 5 and Java 6 Copyright 2006-9 LearningPatterns Inc. All rights reserved. 6

Session 1: Introduction Session 1: Introduction Overview EJB 3.0 Copyright 2006-9 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.0, its goals, and the problems with earlier versions Copyright 2006-9 LearningPatterns Inc. All rights reserved. 8

Session 1: Introduction Overview Overview EJB 3.0 Copyright 2006-9 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-9 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-9 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-9 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-9 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-9 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, the 2 was dropped from the name Copyright 2006-9 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-9 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-9 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-9 LearningPatterns Inc. All rights reserved. 18

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

Session 1: Introduction EJB 3.0 Overview Complete reworking of EJB specification Major differences from EJB 2.x Some areas have changed completely Uses Java 5 annotations heavily Reduces the use of XML configuration files (Deployment Descriptor), and can eliminate them Persistence is completely different 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-9 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-9 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-9 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-9 LearningPatterns Inc. All rights reserved. 23

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-9 LearningPatterns Inc. All rights reserved. 24

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 J2EE 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-9 LearningPatterns Inc. All rights reserved. 25

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-9 LearningPatterns Inc. All rights reserved. 26

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-9 LearningPatterns Inc. All rights reserved. 27

Lab 1.1: Setting up the Environment Lab 1.1 Setting Up the Environment Copyright 2006-9 LearningPatterns Inc. All rights reserved. 28

Lab 1.1: Setting up the Environment Lab 1.1 Set up the Server Lab Overview: In this lab you will become familiar with and set up your application server and development environment The server you'll be using is the JBoss Application Server The development environment is the Eclipse IDE You'll also set up the lab directory Objectives: Set up the JBoss application server Set up the development environment Become familiar with starting and stopping JBoss Review some of the JBoss monitoring tools Builds on previous labs: None Approximate Time: 20-30 minutes Copyright 2006-9 LearningPatterns Inc. All rights reserved. 29

Lab 1.1: Setting up the Environment Information Content and Task Content Lab Within a lab, information only content is presented in the normal way the same as in the student manual pages Like these bullets at the top of the page Tasks that the student needs to perform are in a box with a slightly different look to help you identify them An example appears below Tasks to Perform Look at these instructions, and notice the different look of the box as compared to that above Make a note of how it looks, as future labs will use this format OK Now get out your setup CD; we're ready to start working Copyright 2006-9 LearningPatterns Inc. All rights reserved. 30

Lab 1.1: Setting up the Environment Extract the Lab Setup Zip File Lab To set up the labs, you'll need the setup zip file for the course This will either be on a CD for the course, or given by the instructor The file name should be EJB3_LabSetup_.zip Our base working directory for this course will be C:\StudentWork\EJB3 This directory will be created when we extract the Setup zip It includes a directory structure and files (e.g., Java files, XML files, other files) that will be needed in the labs All instructions assume that this zip file is extracted to C:\. If you choose a different directory, please adjust accordingly Tasks to Perform Unzip the lab setup file to C:\ This will create the directory structure, described in the next slide, containing files that you will need for doing the labs The CD will also contain the following folders Resources: Documentation, specifications, etc. Copyright 2006-9 LearningPatterns Inc. All rights reserved. 31

Lab 1.1: Setting up the Environment Lab Directory Structure Lab StudentWork\EJB3 contains Derby: Database files Resources : Extra files (e.g. docs) Setup: Files needed for lab work workspace: Lab working directories StudentWork\EJB3\workspace contains the following folders: LabNN : Lab directories LabNN\build\classes : compiled code * LabNN\bin : compiled code * LabNN\src\ : Java source files LabNN\src\META-INF\: ejb-jar.xml (if used), etc There are two folders used by Eclipse for compiled Java code For an EJB Project, the folder build\classes is used For a regular Java project, the folder is bin These folders are created by Eclipse when you create the project We'll learn more about the projects in later labs Some of the labs are Web applications These labs will include additional Web related directories The LabNN\WebContent and LabNN\WebContent\WEB-INF directories Copyright 2006-9 LearningPatterns Inc. All rights reserved. 32

Lab 1.1: Setting up the Environment The JBoss Application Server Lab We will be using JBoss as our application server It is an open source, J2EE Application server It is full featured, and used very widely by developers Fast growing market share for production We will use it for our labs Very easy to use Highly scalable Advanced features Open Source! Supported by JBoss Group Inc. (a division or Red Hat) For profit corporation created to support users of JBoss with Production and Development support Copyright 2006-9 LearningPatterns Inc. All rights reserved. 33

Lab 1.1: Setting up the Environment Setup Environment Lab Tasks to Perform Make sure that you have Java 5 installed Likely installed in a directory like C:\Program Files\Java\jdk1.5.x It's best to set the following environment variables for Java 5: JAVA_HOME=C:\Program Files\Java\jdk1.5.x (e.g., 1.5.0_11) Add entries to the PATH environment variable PATH should include %JAVA_HOME%\bin (for the JDK) Make sure JBoss is installed in a directory like C:\jboss-4.2.2.GA (JBoss 4) or C:\jboss-5.0.1.GA (JBoss 5) If it isn't installed, download it from www.jboss.org and install Make sure that Eclipse is installed - usually in C:\eclipse If it isn't installed, download it from www.eclipse.org and install * If any software was installed in a different directory, you'll need to modify the instructions in the lab to refer to your install directory Set the environment variable permanently via the Control Panel by going to: System Advanced tab Environment Variables The value for JAVA_HOME shown above is based on your installing Java 5 in the normal location If you've installed it in a different location, then adjust the value accordingly Setting this will ensure that Eclipse uses the Java version you want it to The Eclipse version you should use is the Ganymede - IDE for Java EE Developers The JBoss and Eclipse installs are zip files - just unzip them A common location is to C:\ but you can unzip the anywhere, as long as you know where, and you modify the lab instructions to refer to your correct locations Copyright 2006-9 LearningPatterns Inc. All rights reserved. 34

Lab 1.1: Setting up the Environment The Eclipse Development Environment Lab Eclipse is an open source platform for building integrated development environments (IDEs) Used mainly for Java development Can be extended via plugins to create applications useful in many areas (e.g. C# programming) http://www.eclipse.org is the main website The remainder of this lab gives detailed instructions on using Eclipse to work with the JBoss server Starting Eclipse, creating and configuring servers Many labs in the course do not include specific details regarding Eclipse they just say build/deploy as before For these labs, you should use the same procedures to build/deploy as in the first lab where a task is done Refer back to previous lab instructions as needed The Eclipse source base was originally developed by IBM It was released by IBM into open source IBM's RAD environment is built on top of Eclipse Copyright 2006-9 LearningPatterns Inc. All rights reserved. 35

Lab 1.1: Setting up the Environment Launch Eclipse Lab Tasks to Perform To launch eclipse, go to c:\eclipse and run eclipse.exe Dialog box should appear prompting for workbench location Set the workbench location to C:\StudentWork\EJB\workspace If a different default Workbench location is set, change it Click OK In the window that opens, click the Workbench icon If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly You can put a shortcut to this executable on your desktop Copyright 2006-9 LearningPatterns Inc. All rights reserved. 36

Lab 1.1: Setting up the Environment The J2EE Perspectice Lab Eclipse starts up in the J2EE Perspective - shown below Note the Servers view at bottom, which we'll use soon For basic information on Eclipse, go to the end of this lab Copyright 2006-9 LearningPatterns Inc. All rights reserved. 37

Lab 1.1: Setting up the Environment Create a Server Instance Lab Tasks to Perform We'll configure a JBoss server in Eclipse to run our services 1. Go to the Servers view, right click in it, and select New Server 2. In the next dialog, select JBoss 4.2 or JBoss 5.0 * and click Next 3. In the next dialog, configure the server install directory, & click Next 4. The defaults should be fine in the next dialog (ports and server config) 5. Click Finish (See next slide for any problems with JBoss 5 server) 1 2 3 Screen shots are based on JBoss 4.2.2 Select the server that you are using (JBoss 4 or JBoss 5) The images above show us configuring a JBoss 4.2.2 GA server The standard JBoss 4.2.2 location is C:\jboss-4.2.2.GA The standard JBoss 5.0.1 location is C:\jboss-5.0.1.GA If you have a different version, or have installed JBoss in a different directory, then configure the server accordingly Eclipse assumes the default ports for JBoss - which are shown in the next to last dialog If your server is using different ports, configure these accordingly Likewise, if you are not using the default server configuration, then change this accordingly. Note that you want to create the server before we do any other labs Creating a server sets up a server runtime, which needs to be associated with lab projects that we'll create later (this will be done automatically by Eclipse if you have only one server runtime in the workspace) Copyright 2006-9 LearningPatterns Inc. All rights reserved. 38

Lab 1.1: Setting up the Environment Eclipse/JBoss 5 Server Creation Problem Lab If you are using JBoss 5 with Eclipse you may see the following error when setting the Application server directory "Missing classpath entry C:\jboss-5.0.1.GA\server\default\lib\mail.jar" Caused by a bug in the JBoss 5 server def of Eclipse 3.4 If you don't see the error, ignore this slide Otherwise, follow the instructions below to fix this problem Exit Eclipse Tasks to Perform Go to StudentWork\EJB3\Setup\Lab01.1, and copy the file jboss5.serverdef to C:\eclipse\plugins\org.eclipse.jst.server.generic.jboss_nnn\servers * Restart Eclipse, and try to create the server again - it should work If you have installed Eclipse in a location other than the default (C:\Eclipse), then adjust the directory locations given above accordingly The name of the directory under C:\eclipse\plugins will be something like: org.eclipse.jst.server.generic.jboss_1.5.205.v200805140145 The numbers in this name will vary depending on which version of Eclipse you have installed Copyright 2006-9 LearningPatterns Inc. All rights reserved. 39

Lab 1.1: Setting up the Environment Start the JBoss Server Lab Tasks to Perform Right click on the server in the Servers view, and select Start This will start up the server and produce copious debugging information in the console view, as shown below To restart (stop/start) a server, right click and select Restart To stop a server - right click and select Stop See notes for other useful information on controlling the server Screen shots are based on JBoss 4.2.2 The screen shots are from JBoss 4.2.0 - other releases will be similar Note - if you have problems timing out when starting, you can change the server configuration Double click on the server in the Servers view A window will open in the editor, that allows you to edit various configuration settings You can change the Timeout settings here -e.g., if you have a slow machine, you may need to increase the default timeout for starting the server from the default of 50 seconds You can also change the Publishing settings, which determine how and when Eclipse pushes any changes you make to the server - for example, you may not want to publish automatically, as this can be annoying if a partially changed project gets published Note - Check the JBoss console for exceptions - sometimes there are port conflicts starting JBoss If this happens, you can open a command prompt, and execute netstat -o to see the ports in use, and the PID of the process using it You can then go to Task Manager to see what process is associated with the given PID, and hopefully shut the process down so you can boot JBoss Note that the Eclipse/JBoss coordination appears to depend on several services deployed in JBoss For example - JNDI and the Remote Invoker Adapter If you have a custom JBoss configuration, it would need to support all the needed service Copyright 2006-9 LearningPatterns Inc. All rights reserved. 40

Lab 1.1: Setting up the Environment JBoss Web Console Lab You can monitor some basic server statistics with the JBoss Web Console The Web Console is a web application located (by default) at: http://localhost:8080/web-console Tasks to Perform Launch a browser, point to the URL above You will need to have the Java Plug-in installed for your browser to run the console If you don't have the java plug-in installed, you can look at the jmx console instead: http://localhost:8080/jmx-console If you have configured your server or ports differently from the standard installation, the URL for the consoles will need to conform to your hostname and HTTP port Copyright 2006-9 LearningPatterns Inc. All rights reserved. 41

Lab 1.1: Setting up the Environment JBoss Web Console Lab Tasks to Perform Click the JBoss Management Console node at the upper left This will show some basic server statistics on the right Copyright 2006-9 LearningPatterns Inc. All rights reserved. 42

Lab 1.1: Setting up the Environment Look at Documentation Lab Tasks to Perform Look at the EJB3 & JPA javadocs located in the Resources folder Unzip the zip file in this directory onto your computer Open the docs\api\index.html file and look at it This is the main javadoc page for the Java 5 EE documentation * There is also a helper sheet for EJB3 annotations called ejb3.0-anno-cheat-1.2.pdf It's a good idea to download and look at the EJB3 specs * ejb-3_0-fr-spec-simplified.pdf: Overview document for EJB3 ejb-3_0-fr-spec-ejbcore.pdf: Specification for EJB3, not including persistence API ejb-3_0-fr-spec-persistence.pdf: Specification for JPA (Java Persistence API) STOP The EJB-3 specs can be downloaded from Sun's web site http://java.sun.com/products/ejb/docs.html The specification shouldn't be the first thing you read, but it is valuable after you have some understanding of EJB3 The javadocs are NOT the complete Java 5 EE javadoc To save space, we've only supplied the EJB-3 relevant docs The documentation is important Come back to it later when you have questions about the API or the specification ejb3.0-anno-cheat-1.2.pdf is not part of the official documentation It has been included just to help you keep track of the annotations Copyright 2006-9 LearningPatterns Inc. All rights reserved. 43

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.0 better than previous versions of EJB? Copyright 2006-9 LearningPatterns Inc. All rights reserved. 44

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-9 LearningPatterns Inc. All rights reserved. 45

Session 1: Introduction Lesson Summary EJB 3.0 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 Copyright 2006-9 LearningPatterns Inc. All rights reserved. 46

Session 6: Exception Handling and Best Practices Session 6: Exception Handling and Best Practices Exception Handling EJB 3 Best Practices Copyright 2006-9 LearningPatterns Inc. All rights reserved. 345

Session 6: Exception Handling and Best Practices Lesson Objectives Become familiar with exceptions, and how Java classifies them Understand how EJB functions with respect to exceptions Understand core design principles for using EJB Copyright 2006-9 LearningPatterns Inc. All rights reserved. 346

Session 6: Exception Handling and Best Practices Exception Handling Exception Handling EJB 3 Best Practices Copyright 2006-9 LearningPatterns Inc. All rights reserved. 347

Session 6: Exception Handling and Best Practices Overview of Exceptions Exceptions in Java are used to notify calling code of some unusual condition In general, they are used to signal errors, either in your code, or in the input obtained from the user, a database, etc. Exceptions are objects in Java They are not errors; they are used to handle errors The type (or class) of the exception object indicates the kind of exception The exception object may have data that can be used to convey information about the exception Exceptions cause a jump in program flow The program must stop what it is doing and respond to the exception Copyright 2006-9 LearningPatterns Inc. All rights reserved. 348

Session 6: Exception Handling and Best Practices Exception Hierarchy Throwable Exception Error Other Exception Classes RuntimeException Checked exceptions Unchecked exceptions Java divides exceptions into broad categories To help organize how you deal with them in your code Exceptions that must be handled, or declared in a throws clause, are checked exceptions "Checked" means checked by the compiler Such exceptions must be handled in some way, and the compiler enforces this Code that does not handle checked exceptions will not compile All others are called unchecked exceptions You are not forced to handle unchecked exceptions (by the compiler) You might wish to handle some of them It's unlikely that you'll want to explicitly handle things like NullPointerException In general, you won't use Throwable directly it is subclassed into two main branches Exception a subclass of Throwable that programs must handle in some way Error a subclass of Throwable for abnormal events that should not normally occur, such as an out-of-memory condition do not try to handle Errors unless you really know what you are doing Exceptions are further categorized by subclassing into RuntimeException a subclass of Exception which can't be foreseen before runtime, thus the compiler cannot enforce the handling of them Copyright 2006-9 LearningPatterns Inc. All rights reserved. 349

Session 6: Exception Handling and Best Practices Application Exceptions in EJB An application exception is an exception defined by the Bean Provider as part of the business logic of an application Used by business methods to inform the client of abnormal application-level conditions, such as unacceptable values of the input arguments to a business method The client is expected to deal with the exception A client can typically recover from an application exception Not intended for reporting system-level problems For example, an Account bean may use an application exception to report that a withdraw operation can't be performed because of insufficient funds An application exception may be defined in the throws clause of a method of an enterprise bean s business interface Copyright 2006-9 LearningPatterns Inc. All rights reserved. 350

Session 6: Exception Handling and Best Practices Defining Application Exceptions The Bean Provider defines application exceptions An application exception may be a checked exception Checked exceptions listed in the methods of the beans business interface are automatically considered application exceptions An application exception may be an unchecked (runtime) exception that is defined as an application exception by annotating it with @ApplicationException Application exceptions should only be used for reporting business logic exceptions Should not be used to report system exceptions They are designed to be handled by the client An application exception may not be a subclass of the java.rmi.remoteexception The java.rmi.remoteexception and its subclasses are reserved for system exceptions Copyright 2006-9 LearningPatterns Inc. All rights reserved. 351

Session 6: Exception Handling and Best Practices Application Exception Example // Checked exceptions are automatically application exceptions public class ItemNotFoundException extends Exception { //... } // Declare a Runtime exception to be an application exception @ApplicationException public class MyRuntimeException extends RuntimeException { //... } If your application exception is a checked exception, you would need to declare it in the business interface for any business method that might throw it public interface Catalog { public void removeitem(musicitem item) throws ItemNotFoundException; public void additem(musicitem item); } Copyright 2006-9 LearningPatterns Inc. All rights reserved. 352

Session 6: Exception Handling and Best Practices Container Handling of Application Exception If a bean throws an application exception: The container will re-throw the exception exactly as it was received The client will receive the exception exactly as it was thrown by the bean The container will not automatically roll back the current transaction Unless the application exception was defined to cause transaction rollback as shown below @ApplicationException(rollback=true) public class ItemNotFoundException extends Exception { //... } Copyright 2006-9 LearningPatterns Inc. All rights reserved. 353

Session 6: Exception Handling and Best Practices Bean Throwing of Application Exception Before throwing an application exception the bean developer must ensure that the bean does one of the following Ensure that the instance is in a state such that a client s attempt to continue and/or commit the transaction does not result in loss of data integrity For example, throw an application exception indicating an invalid input parameter before performing any database updates If the application exception is not specified to cause transaction rollback, mark the transaction for rollback using the EJBContext.setRollbackOnly method before throwing the application exception This ensures that the transaction can never commit Since the container does not roll back a transaction automatically if an application exception is thrown, it is up to the bean developer to make sure that there is no loss of data integrity Taking either of the above actions will ensure this is the case Copyright 2006-9 LearningPatterns Inc. All rights reserved. 354

Session 6: Exception Handling and Best Practices Client Handling of Application Exceptions Client programs receive application exceptions exactly as thrown The bean instance is also still available to the client, since the container does not remove it The client is responsible for deciding what action to take when it receives an application exception Note that although the container won't automatically roll back an ongoing transaction, the bean instance might have rolled it back The caller should check the transaction state before proceeding This can be done statically by checking documentation to see if the exception was marked for rollback EJB callers can use EJBContext.getRollbackOnly() Non-EJB callers can get a UserTransaction instance to check the status of the transaction A javax.transaction.usertransaction object is available via JNDI lookup in any Java EE compliant application server UserTransaction.getStatus() returns the status of the transaction associated with the current thread Copyright 2006-9 LearningPatterns Inc. All rights reserved. 355

Session 6: Exception Handling and Best Practices System Exceptions Indicate Failure A system exception is an exception that is a java.rmi.remoteexception (or one of its subclasses) or a RuntimeException that is not an application exception If your bean encounters a system exception or some other error, it needs to be handled differently than an application error For example, if a bean can't get a database connection, or if it gets a RemoteException when invoking another EJB These kinds of errors are either unexpected, or non-recoverable If a bean encounters a system exception or error, it should throw a suitable non-application exception It should propagate any system exceptions or errors encountered If it encounters a checked exception it can't recover from, it should throw an EJBException that wraps the original exception It should throw an EJBException for any other errors The guidelines that the specification gives are not mandatory You should follow them unless you have a good reason not to Copyright 2006-9 LearningPatterns Inc. All rights reserved. 356

Session 6: Exception Handling and Best Practices Container Handling of System Exception If a bean throws a system (non-application) exception: The container catches it, logs & throws an exception to the caller The transaction in which the bean method participated will be rolled back Resources acquired through resource factories declared in the enterprise bean environment will be released No other method will be invoked on an instance that threw a nonapplication exception Generally, the container destroys the instance The caller will generally receive an EJBException that wraps the original exception Unless the caller started the transaction, in which case it will receive an EJBTransactionRolledbackException Note that if a bean acquires "unmanaged" resources without involving the container, then the container will not know to release them That's one of the reasons we declare them in the environment so the container can manage them We give the details here for the most common situation of Java clients coding to the EJB 3 API In other situations, the details might differ For example, a Web Service client where the service is implemented by an EJB Or a client invoking an EJB 3 bean through the EJB 2.1 API See the specification for more details on these kinds of situations Copyright 2006-9 LearningPatterns Inc. All rights reserved. 357

Session 6: Exception Handling and Best Practices Client Handling of System Exceptions If an EJB client receives a system exception, it doesn't really know if the invocation completed or not The exception may have occurred in the communication subsystem If the client is executing in the context of a transaction, the client s transaction may, or may not, have been marked for rollback by the communication subsystem or target bean s container If a client is executing in a transaction context it can: Roll back the transaction Check the transaction status, and if it hasn't been rolled back, it can proceed The bean instance that threw the exception will not be valid, so the client has to reacquire an instance, or do something else Copyright 2006-9 LearningPatterns Inc. All rights reserved. 358

Session 6: Exception Handling and Best Practices EJB 3 Best Practices Exception Handling EJB 3 Best Practices Copyright 2006-9 LearningPatterns Inc. All rights reserved. 359