Home Programming EJB 3 Developer Guide

EJB 3 Developer Guide

By Michael Sikora
books-svg-icon Book
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to the EJB 3 Architecture
About this book
Publication date:
May 2008
Publisher
Packt
Pages
276
ISBN
9781847195609

 

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 EE

  • The EJB 3 Architecture

  • Getting 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.

 

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 Manager

  • Object/Relational Mapping

  • The 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 API

  • Metadata Annotations

  • Improved Query Language

  • Use of Defaulting

  • Dependency Injection

  • Simplification 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:

  • Projections

  • GROUP BY and HAVING clauses

  • Joins

  • Subqueries

  • Dynamic Queries

  • Queries with parameters

  • Bulk 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:

The administrator console is used for numerous tasks such as creating and configuring domains, monitoring performance, and deploying applications. An alternative for deploying applications is using the asadmin tool from the command line.

In the remainder of this book we have used the asadmin tool for deployment. By including it as an Ant target the whole process of compiling, packaging, and deploying is automated.

Shutting Down GlassFish

To stop GlassFish use the following command:

asadmin stop-domain domain1

Downloading Example Source Code

The source code for the examples can be found as a zip file on the book's web site. Download the file and unzip it into a drive and directory of your choice. The examples in the book assume the source code has been downloaded into the C:\ directory. Subdirectories correspond to individual chapters: C:\EJB3Chapter02, C:\EJB3Chapter03, and so on. You should consult the readme file before running any scripts.

 

Summary


We gave an overview of the EJB 3 architecture and its relationship to the multi-layer Java EE architecture. EJB technology applies to the business processing and persistence layers of the multi-layer model. There are three main artifacts a business application using EJB technology will develop: session-beans, message-driven beans, and entities.

These artifacts are deployed to an EJB container which provides a number of services. We had a brief look at some of these services. In particular we saw that a separate service, the Java Persistence API, is provided for persisting entities.

Finally we saw how to get started with Sun's open-source GlassFish EJB 3 container. All the examples which follow in this book have been deployed and run on GlassFish.

In the following chapter we will look at developing the EJB component which handles business processing, namely session beans.

About the Author
  • Michael Sikora

    Michael Sikora is an enterprise architect with a background in the Unified Process and JEE. 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 datawarehouse systems. He has experience of 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 www.ejbconsultants.com whilst he also maintains a blog at http://msikora.typepad.com Contact Michael Sikora

    Browse publications by this author
Latest Reviews (1 reviews total)
EJB 3 Developer Guide
Unlock this book and the full library FREE for 7 days
Start now