EJB 3 Developer Guide - Michael Sikora - E-Book

EJB 3 Developer Guide E-Book

Sikora Michael

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail






The EJB 3 (Enterprise Java Beans version 3) specification is a core component of enterprise-level JEE (Java Platform Enterprise Edition) implementations and this improved version is set to simplify the development of Enterprise Java applications.



This book covers the core elements of EJB 3 technology, exploring them in a concise manner with many supporting examples. You will gain a thorough understanding of EJB 3 technology and learn about the most important features of EJB 3 quickly. 

Approach



This book is a fast-paced tutorial that explores the key features of EJB 3 with many accompanying examples. This book is not a complete reference guide, but a concise exploration of EJB 3's core elements.

Who this book is for



This book is primarily aimed at professional developers who already have a working knowledge of Java. Enterprise architects and designers with a background in Java would also find this book of use. Previous experience of working with Java is essential and knowledge of relational databases is desirable.



As this book is an introduction to EJB 3, it is aimed at those who are new to EJB 3. As the new version of EJB is so radically different from the previous version (EJB 2.x), the book is suitable for and should be of interest to those who have had experience working with EJB 2.x. The text makes it clear where the differences between the versions of EJB lie, although they are not explored in detail.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 302

Veröffentlichungsjahr: 2008

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

EJB 3 Developer Guide
Credits
About the Author
About the Reviewers
Preface
What This Book Covers
What You Need for This Book
Who Is This Book For
Approach of this Book
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. Introduction to the EJB 3 Architecture
Introduction to the Java EE Architecture
The EJB 3 Architecture
EJB Container Services
The JPA Persistence Engine
EJB 3 Compared with Earlier Versions
Getting Started
Installing GlassFish
Testing the Installation
Accessing the Administrator Console
Shutting Down GlassFish
Downloading Example Source Code
Summary
2. Session Beans
Introduction
Stateless Session Beans
Annotations
Creating a Session Bean Client
Running the Example
The Program Directory Structure
The Ant Build Script
The Application Client Container
Building the Application
Stateless Session Bean's LifeCycle
Stateful Session Beans
Stateful Session Bean's LifeCycle
Local Interfaces
Summary
3. Entities
Introduction
EJB 3 Entities
Comparison with EJB 2.x Entity Beans
Mapping an Entity to a Database Table
Introducing the EntityManager
Packaging and Deploying Entities
The Program Directory Structure
Building the Application
Field-Based Annotations
Generating Primary Keys
Table Strategy
Sequence Strategy
Identity Strategy
Auto Strategy
Overriding Metadata Defaults
Summary
4. Object/Relational Mapping
O/R Mapping Default Behavior
A Banking Example Application
Customer Entity
Account Entity
Address Entity
Referee Entity
Testing the Application
O/R Mapping Overriding Defaults
Customer Entity
Account Entity
Address Entity
BankServiceBean
O/R Mapping Additional Annotations
Referee Class
BankServiceBean
Composite Primary Keys
O/R Inheritance Mapping
SINGLE_TABLE Strategy
JOINED Strategy
Table per Concrete Class Strategy
Summary
5. The Java Persistence Query Language
Introduction
Simple Queries
Projection
Conditional Expressions
Aggregate Functions
GROUP BY
HAVING
Queries with Relationships
Joins
Inner Joins
Outer Joins
Fetch Joins
Collection Comparison Expressions
Constructor Expressions
SubQueries
Functions
CONCAT
SUBSTRING
TRIM
LOWER and UPPER
LENGTH
LOCATE
ABS
SQRT
MOD
SIZE
Queries with Parameters
Positional Parameters
Named Parameters
Named Queries
Handling Date and Time
@Temporal annotation
Queries with Date Parameters
Datetime Functions
Bulk Update and Delete
Native SQL
Summary
6. Entity Manager
Application-managed Entity Manager
Entity Manager Merge
Entity Manager Methods
remove()
contains()
flush()
setFlushMode()
refresh()
clear()
Cascade Operations
persist
remove
merge
refresh
all
Extended Persistence Context
Entity LifeCycle Callback Methods
Entity Listeners
Summary
7. Transactions
Introduction
Container-Managed Transaction Demarcation
SUPPORTS
NOT_SUPPORTED
REQUIRED
REQUIRES_NEW
MANDATORY
Never
Examples of Transaction Attributes
REQUIRED Example
REQUIRES_NEW Example
NOT_SUPPORTED Example
SUPPORTS Example
MANDATORY Example
NEVER Example
Controlling Container Managed Transactions
SessionSynchronization Interface
Doomed Transactions
Concurrency and Database Locking
Isolation Levels
Lost Update Problem
Versioning
Read and Write Locking
UserTransaction Interface
Summary
8. Messaging
Introduction
Java Message Service (JMS) API
Queue Producer and Consumer Examples
Synchronous Queue Consumer Example
Running the Queue Producer and Synchronous Queue Consumer Examples
An Asynchronous Queue Consumer Example
Running the Asynchronous Queue Consumer Example
Topic Producer and Consumer Examples
Synchronous Topic Consumer Example
Running the Topic Producer and Synchronous Topic Consumer Examples
An Asynchronous Topic Consumer Example
Running the Asynchronous Topic Consumer Example
Motivation for Message-Driven Beans
A Simple Message-Driven Bean Example
A Session Bean Queue Producer
A Message-Driven Bean Queue Consumer
MDB Activation Configuration Properties
acknowledgeMode
subscriptionDurability
messageSelector
MessageDrivenContext
MDB LifeCycle
MDB Example Revisited
Sending Message Confirmation to a Client
MDBs and Transactions
Summary
9. EJB Timer Service
Introduction
Timer Service Examples
A Single Event Example
An Interval Event Example
A Timer Interface Example
Timers and Transactions
Summary
10. Interceptors
Interceptor Methods
Interceptor Classes
Default Interceptors
Interceptor Communication
Summary
11. Implementing EJB 3 Web Services
Overview of Web Service Concepts
The SOAP Protocol
The WSDL Standard
The UDDI Standard
SOA and Web Services
Creating a Java Application Web Service
Creating an Endpoint Implementation Interface
The WSDL Document
The <portType> Element
The <binding> Element
The <service> Element
The <message> and <types> Elements
The GlassFish WSGEN Tool
Deploying a Java Application as a Web Service
The GlassFish Admin Console Test Harness
Creating a Java Web Service Client
Overriding JAX-WS Annotation Defaults
Deploying an EJB Session Bean as a Web Service
Packaging an EJB Web Service
Creating an EJB Web Service Client
Summary
12. EJB 3 Security
Java EE Container Security
Authentication
GlassFish Authentication
Mapping Roles to Groups
Authenticating an EJB Application Client
EJB Authorization
Declarative Authorization
Denying Authorization
EJB Security Propagation
Programmatic Authorization
Java EE Web Container Security
Web-Tier Authorization
Transport Layer Security
Web-Tier Authentication
Example of Web-Tier Authentication and Authorization
Summary
A. Annotations and Their Corresponding Packages
Index

EJB 3 Developer Guide

Michael Sikora

EJB 3 Developer Guide

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2008

Production Reference: 1160508

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847195-60-9

www.packtpub.com

Cover Image by Michelle O'Kane (<[email protected]>)

Credits

Author

Michael Sikora

Reviewers

Meenakshi Verma

Chris Mawata

Lawrence Bean

Senior Acquisition Editor

Douglas Paterson

Development Editor

Sarah Cullington

Technical Editor

Bhupali Khule

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Brinell Catherine Lewis

Indexer

Monica Ajmera

Proofreader

Angie Butcher

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Michael Sikora is an enterprise architect with a background in the Unified Process and Java EE. He has a particular interest in object oriented and database technology. He has worked for many large UK clients such as ICL Fujitsu, Mercury Communications, Vodafone, and BUPA. He has used Java since 2000. Before that he spent a decade designing and developing database and data warehouse systems. He has experience in Oracle, PL/SQL, and C. In the 1980s he worked for Shell developing exploration software. He graduated in Mathematics from Essex University and has Masters degrees from London University and Imperial College.

Michael currently resides in London, England and enjoys mountaineering and still hopes to complete the seven summits. His website is http://www.ejbconsultants.com.

I would like to thank Arun Zachariah, Amanda Waite, George Wilk, and Paul Hudson for advice, feedback, and help on this book. From the Packt publishing staff, I would like in particular to thank Douglas Paterson for his interest in this project. I would also like to thank Sarah Cullington, Brinell Lewis, and Bhupali Khule for the smooth running of the publishing process. Finally I would like to thank the technical reviewers for some very helpful suggestions.

About the Reviewers

Meenakshi Verma has been part of the IT industry since 1998. She is experienced in putting up solutions across multiple industry segments using Java/J2EE technologies. She is currently based in Toronto, Canada and is working with Sapient, a leading North American Consultancy organization. Sapient is a global organization which has offices across North America, Europe and India.

Meenakshi has been helping with technical reviews for books published by Packt Publishing across varied enterprise solutions. Her earlier work includes JasperReports for Java Developers, Java EE 5 Development using GlassFish Application Server, Practical Data Analysis and Reporting with BIRT.

I'd like to thank my husband (Atul Verma) for his encouragement and support throughout the review of this book and many others, and my three year old son (Prieyaansh Verma) for giving me the warmth of his love despite my hectic schedules. I also owe thanks & gratitude to my Father (Mr Bhopal Singh) and Mother (Mrs Raj Bala) for laying a strong foundation in me and giving me their unconditional love and support.

Chris Mawata earned his Masters degree at the University of Western Australia and his Ph.D at the University of Hawaii. He was a professor at the University of Tennessee at Chattanooga for fifteen years after which he went into Java consulting and technical training. He currently trains Java developers and writes course materials for Learning Tree International. He is also sponsored by a National Science Foundation grant to be a Java consultant for Phenotype Screening Corporation.

Lawrence Bean fell out of Computer Science and into Music Education in his sophomore year of college. He graduated with a BA in Music Education from the University of Maine in 1986 and had a ten year career as a Choral Music Educator in the Kennebunk, Maine school system, while continuing his technology pursuits as a hobby. His large non-audition groups won silver at the Events America Choral Festival and his select group was featured on Good Morning America and in Yankee Magazine for their annual performances of traditional christmas carols at the highly acclaimed Kennebunkport Christmas Prelude.

He fell back into Computer Science with the offer of a position as Technology Coordinator at SU#47 in greater Bath, Maine and completed his MS in Computer Science in 2006. For the past ten years he has literally built the school system's technology program, from pulling CAT-5 through the walls and constructing PCs out of spare parts to writing data analysis modules and a custom SIF-compliant Student Information System, while continuing his musical pursuits as a hobby.

Throughout he has been highly involved in the Maine Music Educators Association, American Choral Directors Association of Maine, Association of Computer Technology Educators in Maine, and the Barbershop Harmony Society, holding various positions of responsibility and bringing the Maine All-State Auditions into the 21st century with on-line applications, judging, and results processing.

He has been a strong advocate for free, open-source solutions for public schools and currently presents workshops on IPCop Firewalls and the Koha ILS.

Larry lives with his very patient wife Betsy in Saco, Maine, USA.

Preface

Enterprise JavaBeans (EJB) technology is a core part of the Java EE 5 specification. EJB is a framework for building enterprise-scale object-oriented, distributed, component-based business applications. EJB business applications are written in Java, are scalable and can be deployed on any platform that supports the EJB specification.

EJB applications are deployed to and execute under the control of an EJB container. The EJB container provides services typically required by enterprise applications such as security, transaction management, resource pooling, and systems management.

The EJB 3 specification, released in May 2006, is a radical change from previous versions of the technology. Developing business applications is considerably easier with EJB 3. The handling of persistence in particular has radically changed in EJB 3. Persistence is no longer a service provided by an EJB container but rather by a persistence provider conforming to the Java Persistence API (JPA) specification. Java applications which need to be persisted but which do not require the services provided by an EJB container can be persisted outside an EJB container by a JPA persistence provider. In this book we cover JPA as well as the core EJB 3 services.

This book is a concise, example-driven introduction to EJB 3. The best way to learn a new software technology is by studying and trying out programming examples. In this book you will see a lot of code and one example after another. We do not assume any prior knowledge of EJB. However this book does assume at least a couple of years’ experience of Java and some knowledge of relational database technology. The examples in this book have been deployed on the GlassFish application server. GlassFish was chosen primarily because this is the Java EE 5 reference implementation.

What This Book Covers

Chapter 1 Introduction to EJB 3—A general overview of the Java EE architecture including EJB container services, the JPA persistence engine, and initial installation of the GlassFish application server.

Chapter 2 Session Beans—Creation of a session bean and its client and examples of running it from the application client container. Exploring the program directory structure. Packaging and deploying a session bean. A look at the stateless and stateful session beans lifecycle.

Chapter 3 Entities—Exploring EJB 3 entities. How to package and deploy entities and map an entity to a database table. Metadata defaults and how to override them. Generating primary keys.

Chapter 4 Object/Relational Mapping—One-to-one, one-to-many and many-to-many associations. Default object/relational mapping values and how to override them. Object/relational inheritance mapping and additional annotations.

Chapter 5 JPQL (Java Persistence Query Language)—Looking at different groups of queries including aggregate functions, queries with relationships, subqueries, queries with parameters and named queries. JPQL joins and functions are also explained.

Chapter 6 Entity Manager—Looks in detail at the entity manager. Covers both the EJB 3 container-managed and application-managed entity managers.

Chapter 7 Transactions—ACID properties and isolation levels. Container-managed transactions. Bean-managed transactions.

Chapter 8 Messaging—Looks at the JMS (Java Messaging Service) API. Examples of queue producer and queue consumers. Topic producer and consumers. Message driven beans: their activation configuration properties, lifecycles and transactions.

Chapter 9 EJB Timer Service—Examples of single and interval events. Timer interface methods. Timers and transactions.

Chapter 10 Interceptors—Covers interceptor methods, classes and interceptor communication as well as default interceptors.

Chapter 11 Implementing EJB 3 Web Services—An overview of web service concepts and the web service definition language (WSDL). Creating and deploying a Java application as a web service. Creating and deploying an EJB session bean as a web service. Creating a web service client.

Chapter 12 EJB 3 Security—A look at security, GlassFish authentication, declarative and programmatic EJB authorization and Web Tier authentication and authorization.

The Appendix shows EJB 3 annotations described in this book with their corresponding packages.

What You Need for This Book

First you must have version 5 or higher of the Java Development Kit (JDK). This can be downloaded from http://java.sun.com/javase/downloads/index.jsp.

You also need a version of Ant equal to or higher than 1.6.5. Ant is a tool for building Java programs, similar in concept to the Unix Make tool, except that it is platform independent. Ant is part of Apache’s Jakarta project. If you are unfamiliar with Ant you should look at the Ant web site (http://ant.apache.org/). If you do not have Ant there is no need to download it as the GlassFish application server includes a copy of Ant.

Finally you need a version of GlassFish equal to or higher than V2b41d. This can be downloaded from https://glassfish.dev.java.net//.

Instructions on setting up environment variables and installing GlassFish are given in the "Getting Started" section in Chapter 1.

Who Is This Book For

Previous experience of working with Java is essential and knowledge of relational databases is desirable.

This book is primarily aimed at professional developers who already have a working knowledge of Java. Enterprise architects and designers with a background in Java would also find this book of use.

As this book is an introduction to EJB 3, it is aimed at those who are new to EJB 3. However, as the new version of EJB is so radically different from the previous version (EJB 2.x), the book would also be suitable and of interest to those who have had experience working with EJB 2.x. The text makes it clear where the differences between the versions of EJB lie, although it is not explored in detail.

Approach of this Book

This book has been written for developers new to EJB 3 who want to use the technology. Such readers usually want to see examples and program code. In this book we work through one example after another and we show lots of program code. If you are new to a technology and have looked at your first HelloWorld example, the next thing you want to do is to code and run the program yourself. In the case of EJBs this also means packaging and deploying the EJB to a container. Although we promise no HelloWorld examples in this book, we look at packaging and deployment straight after coding our first EJB, rather than ignoring these topics or leaving them to the end of the book.

All the source code together with packaging and deployment scripts is available from the book's web site.

This book is not a reference book, so we don't attempt to cover all EJB 3 features. We've kept this book concise to help you quickly get up and running with EJB 3.

Although an EJB will run in any EJB container, the deployment process is container-dependent. This means that we need to pick a specific container for our examples. Sun's open-source, free GlassFish container was chosen primarily because this was the Java EE reference container implementation and also because GlassFish has Toplink embedded. Toplink in turn is the reference JPA persistence engine.

We also chose not to use an IDE (Integrated Development Environment) partly because they are all quite different. A book based on IDE A would be of little use to a reader using IDE B. As IDEs are screen-based navigational tools, any resulting book would contain a large number of screenshots and would be at least double in length. More importantly is the author's view that an IDE is not an ideal learning tool. Apart from having to learn to navigate through a large number of screens, often an IDE will hide the underlying EJB technology. Of course once you have learnt EJB an IDE will make you much more productive in your work.

Instead we use the Ant build tool for compiling, packaging, deploying, and running our EJBs.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/5609_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

Chapter 1. Introduction to the EJB 3 Architecture

In this chapter we will give an overview of EJB 3 and how it fits into the Java EE multi-layer framework. We will also look at installing and getting started with the GlassFish container. The topics covered are:

An overview of Java EEThe EJB 3 ArchitectureGetting Started with GlassFish

Introduction to the Java EE Architecture

Modern enterprise applications have their responsibilities divided over a number of layers. A common architecture is the 3-layer model consisting of presentation, business, and database layers. The presentation layer is responsible for presenting a user interface and handling interactions with the end user. The business layer is responsible for executing business logic. The database layer is responsible for storage of business data; typically a relational database management system is used for this layer. Layering is used throughout computer science for managing complexity where each layer serves a distinct purpose.

Java Platform Enterprise Edition (Java EE) technology provides services to enterprise applications using a multi-layer architecture. Java EE applications are web-enabled and Java based, which means they may be written once and deployed on any container supporting the Java EE standard. An application server is the environment in which the container resides. However, in practice we don't need to distinguish between an application server and a container, so we will use the terms interchangeably. The Java EE specification is supported by commercial vendors such as Sun, IBM, Oracle, BEA Systems as well as open-source ventures such as JBoss.

Java EE presentation layer technologies include servlets, JSP pages, and JSF components. These are developed for a business application then subsequently deployed and run in a web container. A client would interact with the web container either from a browser or an applet. In either case the http or https internet protocol would be used for communication.

Enterprise JavaBeans version 3 (EJB 3) is the technology Java EE version 5 (Java EE 5) provides for the business layer. In Java EE 5 we subdivide the business layer into one layer which is concerned with business processing and a second layer which deals with persistence. In EJB 3 the business processing artifacts are session and message-driven beans. These are developed for a business application and deployed and run in an EJB container. The persistence layer artifact is an entity; this is persisted to the database layer using a persistence provider or persistence engine. The persistence engine implements another specification, the Java Persistence API (JPA). Both EJB 3 and the JPA are specifications for which a number of organizations provide implementations. Both specifications can be downloaded from http://www.jcp.org/en/jsr/detail?id=220. The figure below summarizes Java EE 5 architecture:

Note that our 3-layer model has become 5-layers. The distinction between client/web and business logic/persistence layers is not always made. Consequently we refer to Java EE architecture simply as n-layer or multi-layer. A Java EE container offers many other services such as web services, the Java Messaging Service (JMS), and resource adapters.

Note from the diagram that we can access an EJB directly from a Java SE application, such as Swing, without going through a web container. The Java application can be stand-alone, or can be run from an Application Client Container (ACC). An ACC enables a client executing in its own Java Virtual Machine (JVM) outside the EJB container to access a limited number of Java EE services.

The EJB 3 Architecture

The EJB 3 architecture offers a standard for developing distributed, object-oriented, component-based business applications. The components developed in an EJB framework are session and message-driven beans. Collectively these are known as EJBs. These are usually relatively coarse-grained objects encapsulating a business process. They are components in the sense that EJBs can be combined to create a business application. Furthermore if the EJBs have been well designed they can be reused by another application. EJBs are distributed in the sense that they can reside on different computer servers and can be invoked by a remote client from a different system on the network.

A session bean must have a business interface, which can be either remote or local. A remote client invokes the remote interface of a session bean as shown in the following diagram:

However a session bean and its client may reside in the same JVM instance. In such cases the client invokes the local interface of the session bean. The following diagram shows a web container client invoking the session beans local interface:

A message-driven bean is an asynchronous recipient of a JMS message. The client, which can be a Java application or Java EE component such as a session bean, sends a JMS message to a message queue or topic. The message queue or topic may be managed by a Java EE container or alternatively by a dedicated JMS sever. The following diagram shows a client sending a JMS message which is received by a message-driven bean:

EJBs are deployed and run in a container which is designed to make applications scalable, multi-user, and thread-safe. An EJB container also provides a number of services that an enterprise scale business application is likely to need. We will list these services in the next section.

In contrast to session and message-driven beans, entities are relatively fine-grained objects which have a relatively long life and need to be persisted. Prior to EJB 3, entity beans played the role of entities and were defined as remotely accessible components, like session and message-driven beans. In EJB 3 entities are Java objects and so can utilize object-oriented features such as inheritance and polymorphism, which entity beans could not. In EJB 3, entities are persisted by a persistence provider or persistence engine implementing the JPA specification. This persistence engine can run within an EJB container or outside a container where a business application does not require other EJB services.

Strictly speaking EJBs, being remotely accessible components, include only session and message-driven beans and not entities. However, whenever we refer to EJBs we will in general include entities, unless the specific context requires us to make a distinction. When we refer to EJB components, we mean session and message-driven beans and not entities.

EJBs being Java-based may be written once and deployed on any application server supporting the EJB standard.

EJB Container Services

An EJB container provides a large number of services and we will list a few of these here. Much of this book describes some of these services in detail, in particular those which a business application is likely to invoke.

EJB containers support concurrency and all EJB components are thread-safe. EJB containers provide pooling for EJB component instances. Pooling, in particular, contributes to the scalability of the EJB architecture. We will discuss pooling for session beans in Chapter 2 and for message-driven beans in Chapter 8. Load balancing and clustering are EJB container services which also contribute to the scalability of EJB.

EJB containers provide a naming service, the Java Naming and Directory Interface (JNDI), for accessing EJBs or any other container-managed resource such as JMS queue connections. In EJB 3 a simpler annotation-based dependency injection facility is available which in many cases provides an alternative to JNDI. All EJB 3 containers support Java RMI-IIOP (Remote Method Invocation run over Internet Inter-Orb Protocol), which enables a session to be remotely accessed by a client. A client does not need to know whether the invoked EJB is remote or local, residing in the same JVM. This feature is known as location transparency.

Business systems are often transactional and EJB provides a container-managed transaction service. This is described in Chapter 7.

EJB supports messaging by providing JMS-based message-driven beans. We will discuss message-driven beans in Chapter 8.

EJB provides a basic scheduling capability: the Timer service, which is described in Chapter 9.

A new feature of EJB 3 is the Interceptor service. This allows common, tangential aspects of EJB components to be separated from any business logic. This concept is based on AOP (Aspect Oriented Programming) and is described in Chapter 10.

EJB allows you to convert a stateless session bean into a web service; this is covered in Chapter 11.

EJB provides standards for both the authentication and authorization aspects of security. Authentication is concerned with validating the identity of a user. Authorization is concerned with controlling a user's access to an application, or part of an application. We have covered security in Chapter 12.

Last, but certainly not the least, most business applications need a service for persisting entities. In EJB 3 this service is delegated by the container to a Java Persistence API (JPA) persistence engine.

The JPA Persistence Engine

Many applications do not require the services provided by an EJB container but still need persistence services. For this reason JPA has been issued as a separate specification and applications running outside an EJB container can also make use of JPA services. The main services include:

Entity ManagerObject/Relational MappingThe Java Persistence Query Language (JPQL)

The Entity Manager provides services for persistence, transaction management, and managing the lifecycle of entities. Object/Relational metadata annotations are provided for mapping entities onto relational database tables. JPQL is used for retrieving persisted entities. We will look at these in more detail in the forthcoming chapters.

Although the JPA specification is recent, it leverages object/relational mapping technology associated with products such as Hibernate and Oracle Toplink. These products have been available for many years; in the case of Toplink for over a decade. The JPA specification drew heavily on these two products in particular. Furthermore, Toplink and Hibernate are the actual default persistence engines for a number of EJB 3 containers. For example, both Sun's GlassFish container and Oracle Application Server 11g use Toplink as the embedded persistence engine. The JBoss EJB 3 container uses Hibernate as the embedded persistence engine. These are pluggable defaults however, so it is possible to use Hibernate with GlassFish for example.

EJB 3 Compared with Earlier Versions

The main features introduced in EJB 3 can be summarized as:

Simplified Persistence APIMetadata AnnotationsImproved Query LanguageUse of DefaultingDependency InjectionSimplification of Session Beans

The first two features are probably the most important, but we will expand on each of the above features in this section.

The main difference between EJB 3 and EJB 2.x is the handling of persistence which we have already outlined. Prior to EJB 3 there was rather limited object/relational mapping between entity beans and relational tables. Inheritance and polymorphism were not possible prior to EJB 3. An EJB 3 entity is truly a Java object; this could not be said of an entity bean.

The other main EJB 3 innovation is the introduction of metadata annotations. Metadata annotations were first introduced in Java SE 5, so this version of Java or higher must be used when developing EJB 3 applications. Metadata annotations can be used as an alternative to XML deployment descriptors both for configuring EJB components and specifying object/relational mappings with entities. However, deployment descriptors can be used in both cases. We will look at annotation versus deployment descriptor aspects in Chapter 2.

The EJB Query language (EJB QL) available in earlier versions was rather limited in comparison with JPA's JPQL. In particular JPQL provides the following enhancements:

ProjectionsGROUP BY and HAVING clausesJoinsSubqueriesDynamic QueriesQueries with parametersBulk update and delete operations

Extensive use of defaults is made in EJB 3. So, for example, most metadata annotations do not require elements or parameters to be specified, the default is usually common, expected behavior. Annotation elements are usually needed only when we want to configure exceptional behavior.

Dependency injection, first featured in the Spring framework, has been introduced in EJB 3 as an alternative to JNDI for looking up container-managed resources.

Session beans have been simplified. We no longer need to specify component and home interfaces. Furthermore the session bean class no longer has to implement a number of callback interfaces even when these are not required by the application. In EJB 3 these lifecycle callback methods are implemented by session beans only when required.

Getting Started

For this book GlassFish was downloaded on Windows XP and all the examples were run on that platform. The instructions that follow assume a Windows platform is being used, however the installation instructions for other platforms such as Linux/Unix are almost the same.

Installing GlassFish

Before installing GlassFish check that version 5 or higher of the Java Development Kit (JDK) is present on your workstation. This can be downloaded from

http://java.sun.com/javase/downloads/index.jsp

For this book we used JDK 5.0 Update 12.

Set the environment variable JAVA_HOME to point to the directory in which the JDK is installed. Add %JAVA_HOME%\bin, to the PATH environment variable. This is done by clicking Control Panel from the Start menu. Then double-click the system icon. Select the Advanced tab on the System Properties box. Finally click the Environment Variables button.

Next download a version of GlassFish equal to or higher than V2b41d from:

https://glassfish.dev.java.net//

into the directory in which you want to install it. All the code examples in this book were tested with GlassFish version V2b41d. The actual name of the downloaded jar file will depend on the version and platform selected. For this book glassfish-installer-v2-b41d.jar was used. In the same directory as the downloaded jar file, run the jar file as follows:

java -Xmx256m -jar glassfish-installer-v2-b41d.jar

This will unzip the file and create the glassfish subdirectory.

Set the GLASSFISH_HOME environment variable to the directory where GlassFish was installed. Add %GLASSFISH_HOME%\bin to the PATH environment variable.

Set the environment variable ANT_HOME to the directory in which Ant is installed. GlassFish comes bundled with the Ant build tool and the installed Ant directory will be glassfish\lib\ant.

If you already have a version of Ant equal to higher than 1.6.5 then set ANT_HOME accordingly.

Add %ANT_HOME%\bin to the PATH environment variable.

Change the directory to the glassfish directory and complete the installation by running the Ant setup script:

ant -f setup.xml

The setup process may fail because of port conflicts with existing software you may have. If so you will need to edit the setup.xml file. Within the file you should see the following fragment setting up default properties:

..... <property name="domain.name" value="domain1"/> <property name="instance.name" value="server"/> <property name="admin.user" value="admin"/> <property name="admin.password" value="adminadmin"/> <property name="admin.port" value="4848"/> <property name="instance.port" value="8080"/> <property name="orb.port" value="3700"/> <property name="imq.port" value="7676"/> <property name="https.port" value="8181"/> <property name="glassfish.license" value="LICENSE.txt"/> ....

Change the value for the conflicting port, and run setup again.

Testing the Installation

GlassFish is started with the following command:

asadmin start-domain domain1

You should see the following messages:

In particular this shows the admin console URL and the URL for web applications. So enter the URL http://localhost:8080 from a browser. If GlassFish has started up correctly you should get the following page:

Accessing the Administrator Console

Enter the URL http://localhost:4848 from a browser. You should get the following page:

The default user name is admin and the default password is adminadmin. After you have entered these you should get the following page: