You are on page 1of 252

Business Data

Cloud Mobility
Intelligence Centre

Enterprise Computing Solutions

Student Manual

Direccin General de Formacin

CONSEJERA DE EMPLEO,
TURISMO Y CULTURA

Comunidad de Madrid UNIN EUROPEA


FONDO SOCIAL EUROPEO
El Fondo Social Europeo invierte en tu futuro

EDUCATION
S E R V I C E S
.I. n
Developing EJB 3 Applications
with Rational Application

.T ci
Developer v7.5
RD352
Student Manual

.
Volume 1 of 2

C
.F a
C m r
to fo
ec vo
oy si
pr lu
c
Ex
IBM Corporation
Rational software

U.S. Government Users Restricted Rights - Use, duplication or


disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

This information was developed for products and services offered in the U.S.A.

.I. n
IBM may not offer the products, services, or features discussed in this documentation in other
countries. Consult your local IBM representative for information on the products and services
currently available in your area. Any reference to an IBM product, program, or service is not

.T ci
intended to state or imply that only that IBM product, program, or service may be used. Any
functionally equivalent product, program, or service that does not infringe any IBM intellectual
property right may be used instead. However, it is the user's responsibility to evaluate and verify

.
the operation of any non-IBM product, program, or service.

C
.F a
IBM may have patents or pending patent applications covering subject matter described in this
document. The furnishing of this document does not grant you any license to these patents. You
can send license inquiries, in writing, to:

C m
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
r
to fo
For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual
Property Department in your country or send inquiries, in writing, to:
Intellectual Property Licensing
Legal and Intellectual Property Law
ec vo

IBM Japan Ltd.


1623-14, Shimotsuruma, Yamato-shi
Kanagawa 242-8502 Japan

The following paragraph does not apply to the United Kingdom or any other country where
oy si

such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES
CORPORATION PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
pr lu

PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties
in certain transactions, therefore, this statement may not apply to you.
c

This information could include technical inaccuracies or typographical errors. Changes are
periodically made to the information herein; these changes will be incorporated in new editions of
Ex

the publication. IBM may make improvements and/or changes in the product(s) and/or the
program(s) described in this publication at any time without notice.

Any references in this information to non-IBM Web sites are provided for convenience only and
do not in any manner serve as an endorsement of those Web sites. The materials at those Web
sites are not part of the materials for this IBM product and use of those Web sites is at your own
risk.

Licensees of this program who wish to have information about it for the purpose of enabling: (i)
the exchange of information between independently created programs and other programs
(including this one) and (ii) the mutual use of the information which has been exchanged, should
contact:
Intellectual Property Dept.
IBM Corporation
20 Maguire Road
Lexington, Massachusetts 02421-3112
U.S.A.

Such information may be available, subject to appropriate terms and conditions, including in
some cases, payment of a fee.

.I. n
The licensed program described in this document and all licensed material available for it are
provided by IBM under terms of the IBM Customer Agreement, IBM International Program

.T ci
License Agreement or any equivalent agreement between us.

Any performance data contained herein was determined in a controlled environment. Therefore,

.
the results obtained in other operating environments may vary significantly. Some measurements
may have been made on development-level systems and there is no guarantee that these

C
.F a
measurements will be the same on generally available systems. Furthermore, some
measurements may have been estimated through extrapolation. Actual results may vary. Users of
this document should verify the applicable data for their specific environment.

C m
Information concerning non-IBM products was obtained from the suppliers of those products, their
published announcements or other publicly available sources. IBM has not tested those products
and cannot confirm the accuracy of performance, compatibility or any other claims related to non-
r
IBM products. Questions on the capabilities of non-IBM products should be addressed to the
to fo
suppliers of those products.

All statements regarding IBM's future direction or intent are subject to change or withdrawal
without notice, and represent goals and objectives only.
ec vo

This information contains examples of data and reports used in daily business operations. To
illustrate them as completely as possible, the examples include the names of individuals,
companies, brands, and products. All of these names are fictitious and any similarity to the
names and addresses used by an actual business enterprise is entirely coincidental.
oy si

If you are viewing this information in softcopy, the photographs and color illustrations may not
appear.
pr lu

Trademarks and service marks


IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International
Business Machines Corp., registered in many jurisdictions worldwide. Other product and service
names might be trademarks of IBM or other companies. A current list of IBM trademarks is
c

available on the Web at Copyright and trademark information at


www.ibm.com/legal/copytrade.html
Ex

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered
trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or
other countries.
IT Infrastructure Library is a registered trademark of the Central Computer and
Telecommunications Agency which is now part of the Office of Government Commerce
Intel, Intel logo, Intel Inside, Intel Inside logo, Intel Centrino, Intel Centrino logo, Celeron,
Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered
trademarks of Intel Corporation or its subsidiaries in the United States and other
countries.
Intel trademark information
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or
both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft
Corporation in the United States, other countries, or both.
Microsoft trademark guidelines
ITIL is a registered trademark, and a registered community trademark of the Office of
Government Commerce, and is registered in the U.S. Patent and Trademark Office
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Cell Broadband Engine is a trademark of Sony Computer Entertainment, Inc. in the

.I. n
United States, other countries, or both and is used under license therefrom.
Java and all Java-based trademarks and logos are trademarks of Sun Microsystems, Inc.
in the United States, other countries, or both.

.T ci
Other company, product, or service names may be trademarks or service marks of others.

.
C
.F a
C m r
to fo
ec vo
oy si
pr lu
c
Ex
V5.2
Student Notebook

TOC Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Course description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

.I. n
.T ci
Unit 1. Java EE architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Editions of the Java platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
A timeline: The evolution of the Java platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

.
Standards for enterprise applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6

C
.F a
Java Enterprise Edition V5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Java EE multi-tier application architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

C rm
Another way to view the multi-tier architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
The model-view-controller design pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10
MVC in Java EE applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Java EE components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13
Java EE containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
to fo
Interoperability in enterprise applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Distributed enterprise applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Other distributed component technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
J2EE development pain points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
ec vo

Component APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20


Additional APIs used in this course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21
Java Naming and Directory Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22
The role of deployment descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
oy si

Reviewing annotations in Java SE 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25


Some built-in Java 5 SE annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26
Application files are packaged into archives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
u

Java EE application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29


Java EE resource types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-31
cl

Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Ex

Unit 2. Introduction to EJB 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Defining Enterprise JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
When to use an EJB architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
pr

Enterprise applications need runtime services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5


Features of Enterprise JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
A brief history of EJB technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Java EE 5 and EJB 3.0 value proposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Key themes of the EJB 3.0 specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Key themes of the JPA specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

Copyright IBM Corp. 2008 Contents iii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-11
EJB 3.0 configuration defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-13
Simplified resource access: Dependency injection . . . . . . . . . . . . . . . . . . . . . . . . .2-14
Example of resource injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-15
Using annotations for injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-17
Requesting container services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-18
Transactions are logical units of work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-19
The ACID properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21

.I. n
Transaction example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23
Transaction definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24

.T ci
Default transaction demarcation with EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26
Types of EJB 3 beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29

.
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30

C
.F a
Unit 3. Session EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-1
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2

C rm
Session beans are general-purpose workers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-3
Session beans can have state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4
Reasons to use session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-5
EJB clients: Using EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6
to fo
Session beans have two parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7
Remote clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8
Local clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10
Example: Stateless session bean with remote interface . . . . . . . . . . . . . . . . . . . .3-11
ec vo

Client access to session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-12


The EJB context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13
Rules for writing session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15
Application bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-16
oy si

WebSphere default bindings for bean interfaces . . . . . . . . . . . . . . . . . . . . . . . . . .3-17


Stateful session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-19
Life cycle of stateless session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-20
u

Life cycle of stateful session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-21


Web clients and stateful session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-22
cl

Removing stateful session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-23


Exception handling in session beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-24
Comparing stateful and stateless session beans . . . . . . . . . . . . . . . . . . . . . . . . . .3-25
Ex

Typical session bean development process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-26


Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-28
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-29
pr

Unit 4. The library case study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2
The library system and its subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-3
The database used by the library application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4
Use cases in the loan subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-5
Phase 1: Provide basic business operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6
Phase 2: Add entity beans for persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7

iv Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

TOC Phase 3: Add interfaces to the entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8


Phase 4: Complete borrow-return functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Phase 5: Add the user interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Phase 6 and 7: Complete the loan subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
The final application architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13

Unit 5. Strategies for testing EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1

.I. n
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Levels and types of testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

.T ci
Testing EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Testing EJBs using the UTC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Using a unit-test framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6

.
What is JUnit? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7

C
Anatomy of a JUnit 4 test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8

.F a
Anatomy of a test suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
JUnit tools in Rational Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10

C rm
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12

Unit 6. EJB clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1


to fo
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Kinds of EJB clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Session beans can have local and remote clients . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
Remote clients use EJB stub and tie proxies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
ec vo

Dependency injection by EJB clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6


More about the @EJB annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Default resolution of EJB annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Visualization of client interaction with session bean . . . . . . . . . . . . . . . . . . . . . . . . 6-9
oy si

Review of JNDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10


Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11
Java client applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12
u

Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14
cl

Unit 7. Introduction to the Java Persistence API (JPA) . . . . . . . . . . . . . . . . . . . . . . 7-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Ex

Java support for persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3


Three areas of Java persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Introducing Java Persistence API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Entity objects provide persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
pr

Typical application architecture with JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7


Primary features of JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
The nature of entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Example entity class for the simplest situation . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
Entity class requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12
Field-based and property-based access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-13
Example of another JPA entity class: Account . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14

Copyright IBM Corp. 2008 Contents v


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Elements of a JPA persistence provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-15


The entity manager controls entity life cycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-17
The persistence context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-19
Managing the life cycle of an entity instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-20
Life cycle examples (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-21
Life cycle examples (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-22
Handle detached entities with care . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-23
Relationships in JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-24

.I. n
The two types of entity managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-25
Injecting the entity manager into a session bean . . . . . . . . . . . . . . . . . . . . . . . . . .7-26

.T ci
Accessing the entity manager from a Java application . . . . . . . . . . . . . . . . . . . . . .7-27
Persistence units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-28
Packaging persistence.xml with code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-30

.
A generic persistence.xml file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-31

C
A persistence.xml for WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . .7-33

.F a
JPA entity life cycle callback methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-34
JPA entity life cycle listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-35

C rm
Example JPA entity life cycle listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-36
Checkpoint questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-37
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-38
to fo
Unit 8. Object-relational mapping with JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-1
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2
Object-relational mapping strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-3
Example Entity bean from the library case study . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4
ec vo

Using annotations and deployment descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-5


Controlling JPA assumptions: Schema attributes . . . . . . . . . . . . . . . . . . . . . . . . . . .8-7
Data types allowed in persistent fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-8
Annotations for data type mappings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-10
oy si

Primary keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12


Primary key class requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13
Identity annotations allow simple and compound keys . . . . . . . . . . . . . . . . . . . . . .8-14
u

Primary key class example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-15


Embedded class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16
cl

Collections in entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17


Overview of relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18
Graphical depiction of relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-19
Ex

Annotations for multiplicity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-20


Direction of relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-21
Attributes of relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-22
Examples of relationships from the library application . . . . . . . . . . . . . . . . . . . . . .8-24
pr

The challenge of concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-25


Database aids for data consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-26
The concurrency balancing act . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-27
Managing concurrency with JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-28
Optimistic locking requires a version property . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-29
Implementing optimistic locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-30
Additional JPA locking strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-32

vi Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

TOC Application Developer persistence mapping tools . . . . . . . . . . . . . . . . . . . . . . . . . 8-33


Object-relational design strategies revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-34
Checkpoint (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-35
Checkpoint (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-37

Unit 9. Java Persistence Query Language (JPQL) . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

.I. n
Java Persistence Query Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Select queries retrieve data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4

.T ci
Example JPQL select queries on one table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Examples of JPQL select queries on multiple tables . . . . . . . . . . . . . . . . . . . . . . . 9-6
JPQL reference information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8

.
JPQL supports two types of queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9

C
Creating named queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10

.F a
Queries with parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11
Queries with temporal parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12

C rm
Processing query results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13
Update and delete queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-14
Running bulk updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-15
Review of the Query interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-17
to fo
Using SQL queries (introduction to native queries) . . . . . . . . . . . . . . . . . . . . . . . . 9-18
Issuing dynamic SQL in a native query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-19
Issuing precompiled SQL in a native query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-20
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-21
ec vo

Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-22


oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Contents vii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

ix Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

TMK Trademarks
The reader should recognize that the following terms, which appear in the content of this
training document, are official trademarks of IBM or other companies:
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United

.I. n
States, or other countries, or both:

.T ci
CICS Cloudscape DB2
Notes Rational Tivoli
WebSphere Workplace z/OS

.
C
VMware and the VMware boxes logo and design, Virtual SMP and VMotion are

.F a
registered trademarks or trademarks (the Marks) of VMware, Inc. in the United States
and/or other jurisdictions.

C rm
Intel and Pentium are trademarks or registered trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.
Java and all Java-based trademarks and logos are trademarks of Sun Microsystems, Inc.
to fo
in the United States, other countries, or both.
Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other
countries, or both.
ec vo

UNIX is a registered trademark of The Open Group in the United States and other
countries.
Other company, product, or service names may be trademarks or service marks of others.
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Trademarks x


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

xi Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

pref Course description


Developing EJB 3 Applications for WebSphere Application Server V7

Duration: 5 days

.I. n
Purpose

.T ci
This 5-day instructor-led course teaches students how to build Java
Platform, Enterprise Edition 5 (Java EE 5) applications that use
Enterprise JavaBeans (EJB) 3.0 and the Java Persistence API (JPA).

.
Java EE 5 represents a significant evolution in the Java enterprise

C
.F a
programming model. It provides application developers with
considerable improvements that enhance the development experience

C rm
and, in turn, productivity. In particular, the EJB 3.0 specification in Java
EE 5 provides simplified business logic development, simplified testing
and dependency management, and simplified object-relational
persistence.
to fo
In this course, students learn about the Java EE 5 component model
and the new techniques employed in Java EE 5, such as dependency
injection and annotation-based programming. Students also learn how
to develop and test the supported types of EJB beans (session and
ec vo

message-driven) and JPA entities. Finally, students gain experience


with the various qualities of service provide by the EJB container such
as security and transactions, how to create Web services from EJB
components, and how to develop EJB clients.
oy si

IBM WebSphere Application Server V7 and IBM Rational Application


Developer V7.5 provide complete support for the EJB 3 specification.
u

Hands-on exercises throughout this course give students practical


experience developing EJB components with IBM Rational Application
cl

Developer V7.5 and deploying EJB-based applications to IBM


WebSphere Application Server V7.
Ex

Audience
This course is designed for Java developers.
pr

Prerequisites
Before taking this course, students should have practical experience
with the Java programming language. This knowledge can be gained
by attending one of the following courses:

Copyright IBM Corp. 2008 Course description xi


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

WD152 or VD152, Java SE 5 Programming Fundamentals


JA355 or VD155, Introduction to Java SE 5 Using Eclipse 3.2
Students should also have knowledge of database concepts such as
SQL, primary and foreign keys, joins, and referential integrity.
Some knowledge of Java EE Web development and Web services,
and experience with Rational Application Developer or another

.I. n
Eclipse-based development environment, is also beneficial.

.T ci
Objectives
After completing this course, you should be able to:

.
C
State the purpose and value of using the Enterprise JavaBean

.F a
(EJB) technology
Describe the Java EE 5 application architecture

C rm
Use annotation-based development for EJBs
Explain the relationship between annotations in code and
deployment descriptor files
to fo
Define and use dependency injection and resource injection
Develop and test the various types of EJBs (stateless session,
stateful session, or message-driven) and Java Persistence API
ec vo

(JPA) entities
Use Java persistence query language (JPQL)
Perform object-to-relational mappings (ORM) for persistent data
oy si

Implement persistent entities with associations


Integrate an application with messaging using message-driven
u

beans
cl

Use EJB timers and interceptors


Leverage container services for transaction management
Ex

Create and test EJB clients


Create Web services from EJBs
Apply recommended practices in EJB design and implementation
pr

Use IBM Rational Application Developer V7.5 to develop and test


an EJB 3 application
Deploy an EJB 3-based application to WebSphere Application
Server V7

xii Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

pref Curriculum relationship


This course has been derived from WebSphere Education course
WD350: Developing EJB 3 Applications for WebSphere Application
Server. The library case study is the same, but the exercises have
been changed to use Rational Application Developer V7.5 instead of
Rational Application Developer V7.0 as the development environment.
This course uses WebSphere Application Server V7 as the runtime

.I. n
environment instead of WebSphere Application Server V6.1 with the
EJB 3 Feature pack.

.T ci
A minimal acceptable background in Java programming can be
obtained by completing course JA355: Introduction to Java SE 5 Using

.
Eclipse 3.2 or WD152: Java SE 5 Programming Fundamentals.

C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Course description xiii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

xiv Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

pref Agenda
Day 1
Course introduction
Unit 1: Java EE architecture
Unit 2: Introduction to EJB 3

.I. n
Unit 3: Session EJBs
Exercise 1: Creating your first stateless session bean

.T ci
Unit 4: The library case study
Exercise 2: Preparing for the library case study

.
Unit 5: Strategies for testing EJBs

C
.F a
Day 2

C rm
Exercise 3: Starting to build the library case study
Exercise 4: Creating a stateful session EJB for the library case study
Unit 6: EJB clients
Exercise 5: Developing a Java client application for the library case
to fo
study
Unit 7: Introduction to the Java Persistence API (JPA)
Unit 8: Object-relational mapping with JPA
ec vo

Day 3
Exercise 6: Developing the entity beans for the library case study
Unit 9: Java Persistence Query Language (JPQL)
oy si

Exercise 7: Creating session facades for the entity beans


Unit 10: Message-driven beans
Exercise 8: Adding a message-driven bean to the library case study
u
cl

Day 4
Exercise 9: Importing a Web user interface to the library case study
Ex

Unit 11: Managing transactions in EJBs


Exercise 10: Adding transactional integrity to the library case study
Unit 12: EJB 3 timers and interceptors
Exercise 11: Adding an EJB timer to the library case study
pr

Unit 13: EJBs as Web services

Day 5
Exercise 12: Creating a Web service from a stateless session bean
(optional)

Copyright IBM Corp. 2008 Agenda xv


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit 14: EJB security


Exercise 13: Implementing EJB security for the library case study
Unit 15: Recommended practices for EJB 3
Unit 16: Deployment to WebSphere Application Server V7
Exercise 14: Deploying the library case study (optional)
Unit 17: Course summary

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

xvi Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 1. Java EE architecture

What this unit is about


This unit provides and overview of Java Enterprise Edition (EE). It
describes the EE multi-tier architecture, components, containers,

.I. n
packaging, resources, and data sources of enterprise applications.

.T ci
What you should be able to do
After completing this unit, you should be able to:

.
C
Name the editions of the Java platform and state how they relate to

.F a
each other

C rm
Describe the multi-tier architecture of Java EE
List the services and APIs provided by Java EE containers
Describe some of the issues encountered when developing
enterprise applications in earlier J2EE versions
to fo
Explain the purpose of the Java Naming and Directory Interface
(JNDI)
Describe how Java EE is packaged for deployment
ec vo

Define data sources and resources

How you will check your progress


oy si

Checkpoint
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis thisunit,
unit,you
youshould
shouldbe beable
ableto:
to:
Name
Namethe theeditions
editionsofofthe
theJava
Javaplatform
platformand
andstate
statehow
howthey
they

.I. n
relate
relateto
toeach
eachother
other
Describe
Describethe themulti-tier
multi-tierarchitecture
architectureof ofJava
JavaEEEE

.T ci
List
Listthe
theservices
servicesand andAPIs
APIsprovided
providedby byJava
JavaEEEEcontainers
containers
Describe some of the issues encountered when
Describe some of the issues encountered when developing developing

.
enterprise
enterpriseapplications
applicationsin inearlier
earlier J2EE
J2EEversions
versions

C
.F a
Explain
Explainthethepurpose
purposeof ofthe
theJava
JavaNaming
Namingand andDirectory
Directory
Interface
Interface(JNDI)
(JNDI)

C rm
Describe
Describehow howJava
JavaEE EEisispackaged
packagedfor for deployment
deployment
Define data sources and resources
Define data sources and resources
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

1-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Editions of the Java platform


Java Standard Edition (SE)
A runtime platform for developing and running Java applications
It includes database access, CORBA interoperability, and security

.I. n
for local networks and the Internet

.T ci
SE is the core Java technology platform
Used for stand-alone Java applications and applets

.
Java Enterprise Edition (EE)

C
.F a
A runtime platform used for developing, deploying, and managing
multitier, server-centric applications on an enterprise-wide scale

C rm
Builds on the APIs of Standard Edition
It includes distributed communication, threading control, scalable
architecture, and transaction management
to fo
Java Micro Edition (ME)
Designed for embedded devices and consumer products
ec vo

Copyright IBM Corporation 2008

Figure 1-2. Editions of the Java platform WD352 / VD3521.0

Notes:
oy si

The Java language was originally created by Sun Microsystems. The ongoing development
of the language and Java platform based on that language is governed by the Java
u

Community Process (JCP), a much wider organization in which several companies and
cl

individuals who are leaders in the field participate. IBM is an active member of the JCP.
New specifications and updates to existing specification go through an exacting process
during which they are identified by Java Specification Request (JSR) numbers.
Ex

Each release of Java SE and Java EE includes a number of Java Specification Requests
(JSRs) that have become published specifications. For example, EJB 3 is part of Java EE
5.
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

A timeline: The evolution of the Java platform


This course is based on Java EE 5 and Java SE 6

.I. n
Java EE 5
J2EE 1.3 J2EE 1.4 May 2006
J2EE 1.2 Sept 2001 Nov 2003 EJB 3.0

.T ci
Dec 1999 EJB 2.0 EJB 2.1 JPA
EJB 1.1 + + +
JSP and servlet JCA JAX-RPC JSTL
JDBC JAXP JAXR JAX-WS SAAJ

.
JNDI JMS JAAS JACC JAAS JDO

C
JTS + JTA JMX StAX

.F a
C rm
JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6.0
Jan 1996 Jan 1997 Dec 1998 May 2000 Feb 2002 Sept 2004 Sept 2006
JavaBeans Reflection JNDI assert Generics JAX-WS
to fo
JDBC Swing Regex Annotations JDBC 4
RMI JIT compiler JAXP Autoboxing JAXB, StAX
JCE, JSSE, enumerations
JAAS
Java Web Start
ec vo

Copyright IBM Corporation 2008

Figure 1-3. A timeline: The evolution of the Java platform WD352 / VD3521.0

Notes:
oy si

As of October 2008:
u

Java EE V6 is being developed as JSR 316.


J2SE 7.0 is still in plan.
cl

This course uses the term Java Enterprise Edition or Java EE whenever possible, but the
naming convention changed from version 2 (J2EE) and version 5 (Java EE 5). In reality
Ex

there was no great jump for version 2 to version 5: just the numbering scheme changed.
As brief history of Java numbering:
The original release of Java was called the Java Software Development Kit (SDK), and
pr

the first robust release was JDK 1.1.


The first release of true industrial strength, JDK 1.2, was such a major change that it
was renamed as the Java 2 platform.
When the enterprise edition of the platform was created, the two editions were called
J2SE and J2EE.

1-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty The next releases were numbered 1.3 and 1.4. Each release of J2EE followed and was
built upon the release of J2SE with the same version number.
With the release that would have been numbered 1.5, the Java Community agreed to
adopt a more meaningful naming convention and named the changed the version
number to 5.
With version 5, Java EE adopted the short name Java EE 5, rather than the acronym
J5EE.

.I. n
Version 6, the standard edition, adopted the latest naming convention and was named

.T ci
Java SE 6.0.
Rational Application Developer V7.5, supports Java EE 5 and Web 2.0, as does
WebSphere Application Server V7.

.
C
This course is based on Rational Application Developer V7.5 and WebSphere Application

.F a
Server V7.0. Therefore, the environment is a fully-supported Java EE 5 platform.

C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Standards for enterprise applications


Standards make development quicker and more flexible
You can use development tools from a range of vendors
Skills are transferable between platforms

.I. n
Standard services are available to application code

.T ci
Technology should conform to industry standards
A fundamental Java principle Write once, run anywhere means you

.
develop an application once and deploy on multiple platforms without

C
.F a
recompiling

C rm
Java EE-compliant servers provide services in a standard way
Services are added functionality that the container provides for
components
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-4. Standards for enterprise applications WD352 / VD3521.0

Notes:
oy si

Java is not standardized in a formal way (for example, through the International
Organization for Standardization), but is effectively an industry standard because of the
u

way in which it is developed through industry bodies.


cl
Ex
pr

1-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java Enterprise Edition V5


Java EE 5 is a collection of standards:
Java API for XML Messaging (JAXM) 1.0
Java API for XML Processing (JAXP) 1.2

.I. n
Java API for XML Registries (JAXR) 1.0.8
Java API for XML-Based RPC (JAX-RPC) 1.1.3

.T ci
Java API for XML Web Services (JAX-WS) 2.0
Java Architecture for XML Binding (JAXB) 2.0
Java Authentication and Authorization Service (JAAS) 1.0

.
Java Authorization Contract for Containers (JACC) 1.0

C
.F a
Java Naming and Directory Interface (JNDI) 1.2
Java Transaction API (JTA) 1.1

C rm
Java EE Connector Architecture 1.5
JDBC 2.0 WS-I Basic Profile 1.0 JSP 2.1
EJB 3.0 Java Servlet 2.5 JMS 1.1
SAAJ 1.3 StAX 1.0
to fo
XML and Web services security 1.0
Web Services Metadata for the Java Platform 1.0
And others
Java EE 5 is built on Java SE 5
ec vo

Copyright IBM Corporation 2008

Figure 1-5. Java Enterprise Edition V5 WD352 / VD3521.0

Notes:
oy si

Many of the API listed above are not mentioned again in this course.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Java EE multi-tier application architecture

Client Web Business EIS


tier tier tier tier

.I. n
.T ci
Dynamic
Web pages

.
JSP pages
and servlets

C
.F a
Enterprise
data

C rm
Client Enterprise
applications beans
to fo
Client Java EE
system application server
ec vo

Copyright IBM Corporation 2008

Figure 1-6. Java EE multi-tier application architecture WD352 / VD3521.0

Notes:
oy si

Java EE is designed to support applications with multi-tier architectures. In the diagram


above, the client is tier 0, the Web application is tier 1, enterprise logic is tier 2, and
u

persistence or other enterprise information systems (EIS systems) reside on tier 3.


cl
Ex
pr

1-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Another way to view the multi-tier architecture

Client tier Middle tier Enterprise


information
EJB systems tier

.I. n
Java container
(EJBs)

.T ci
client
Legacy
applications

.
C
Web Relational
Web

.F a
container databases
client
(servlets,

C rm
JSPs, and Enterprise
HTML) resource
planning
Other
J2EE systems
client
to fo
services
(JNDI, JMS,
JavaMail)
ec vo

Copyright IBM Corporation 2008

Figure 1-7. Another way to view the multi-tier architecture WD352 / VD3521.0

Notes:
oy si

This diagram shows how the different containers and components allow the functionality of
an application to be divided into tiers or layers. Software like WebSphere Application
u

Server is often described as application integration middleware.


cl

The middle tier provides the range of services that allow the components in the middle of
this diagram, especially EJBs and entity beans, to integrate with the front-end and
back-end resources that are available within the enterprise.
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The model-view-controller design pattern


The model
Represents the underlying data and business logic

.I. n
Contains no information about the user interface

.T ci
The view
The user interface: what the user sees and interacts with

.
One model can have many views

C
.F a
The controller
Connects the model and the view

C rm
Used to communicate between the model and view
A fourth layer (persistence) is often added to the pattern
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-8. The model-view-controller design pattern WD352 / VD3521.0

Notes:
oy si

MVC has been a widely accepted design pattern for decades. It originated with the C++
and Smalltalk community in the 1980s, and is not a Java concept. However, it works well
u

with the Java n-tier architecture. Separating persistence from the model gives a further
cl

level of abstraction to the model, enhancing the benefits.


MVC is widely adopted because:
Ex

It facilitates and promotes code reuse. Proven code can be reused in many applications
at the same time, without the need for any extra coding.
It helps reduce development time. The model, view, and controller can be developed in
parallel.
pr

It makes code more maintainable. The view can be changed without affecting the
model, and the model can be changed without affecting the view.
Data can be moved without affecting the view or model.

1-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

MVC in Java EE applications


The architecture of Java enterprise applications that have a Web user
interface should be based on MVC

.I. n
Java EE

.T ci
Controller Model
server
Java bean
Servlets and EJB

.
Client components

C
.F a
Browser
View

C rm
Persistence
JSP pages
to fo
Database
ec vo

Copyright IBM Corporation 2008

Figure 1-9. MVC in Java EE applications WD352 / VD3521.0

Notes:
oy si

Frameworks such as struts and JSF conform to the MVC design pattern in that they use
JSP pages to present information to the user and servlets to direct the flow of user input to
u

components that perform tasks in response to user requests. Such an implementation of


cl

MVC is appropriate regardless of whether the Web application implements the controller
servlet design pattern in which one servlet is the entry point for all user input, or has
multiple servlets. Typically the servlet layer that makes up the controller includes helper
Ex

classes. Often these helper classes comply with the command design pattern in that they
gather all the information required to perform a desired action and then issue a method call
to execute the command.
Doing the work to execute the commands is the task of the model tier. Typically, requests
pr

forwarded to the model layer result in activities that change the persistent state of the
application. Ideally this real work is performed in coarse-grained chunks that can be
committed or rolled back as logical units of work. In other words, transactional integrity is
required in the model and persistence tiers. Databases and other systems that reflect the
state of the business are sometimes called back-end systems because they are at the
opposite side of a layered application from the front-end or user interface.

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-11


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The model tier should be oblivious to what the application looks like to the user and how it
is used. The view tier should have no knowledge or influence on how business functionality
is performed and how business operations map to user requests and responses. Together,
these two principles make up the basis of model-view separation.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

1-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java EE components
Java EE defines four categories of components
All four must be supported by any Java EE application server

.I. n
Enterprise JavaBeans (EJB) components

.T ci
Distributed, transactional components for business logic
Also called business components on the business tier

.
Web components

C
.F a
Servlets, JavaServer Faces, and JavaServer Pages
Make up Web applications

C rm
Application clients
Java programs that execute on a
client machine and access
to fo
other Java EE components Thin client Fat client

Applets
Graphical Java components that typically execute within a browser
ec vo

Copyright IBM Corporation 2008

Figure 1-10. Java EE components WD352 / VD3521.0

Notes:
oy si

A Java EE component is a self-contained functional software unit that is assembled into a


Java EE application with its related classes and files, and that communicates with other
u

components.
cl

Resource adapters are also part of the Java EE specification. There is no special container
for resource adapters; they typically run in the EJB container and use the same services as
EJB, such as transactions, security, and job management.
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-13


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Java EE containers
Containers manage the execution of Java EE components
Also provide basic services components can access
Container settings determine the level to which components

.I. n
are supported by such things as:

.T ci
Security
Transaction management
Remote connectivity

.
HTTP

C
HTTPS

.F a
Browser

C rm
Web
container

RMI/IIOP
to fo
Application
EJB
client
CLIENT SERVER container
container
ec vo

Copyright IBM Corporation 2008

Figure 1-11. Java EE containers WD352 / VD3521.0

Notes:
oy si

In the diagram above each oval is a different kind of container. Missing, and of less interest,
is the applet container that is provided by Web browsers.
u
cl
Ex
pr

1-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Interoperability in enterprise applications


Components may need to use a range of resources
Resource providers may use different component models
The hosting servers may be different

.I. n
Clients may be written in different languages

.T ci
Goal: interoperability should be simple and reliable
The technology should be compatible with existing server

.
platforms

C
.F a
Components should be able to communicate with resources
provided on other platforms

C rm
Other component models should be supported
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-12. Interoperability in enterprise applications WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-15


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Distributed enterprise applications


Enterprise applications often need to be distributed:
When services are available but on separate machines
To satisfy a redundancy requirement

.I. n
To improve performance through load balancing

.T ci
Integrating independent systems to act as a single system

WebSphere Application Server supports clustering of several

.
servers into one configuration

C
.F a
Goal:

C rm
A distribution mechanism should be available for applications
The mechanism should be easy to use
Load balancing and redundancy should be handled automatically
to fo
In a WebSphere Application Server clustered environment
failover provides high availability
ec vo

Copyright IBM Corporation 2008

Figure 1-13. Distributed enterprise applications WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

1-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Other distributed component technologies


Java Remote Method Invocation (RMI)
The Java-to-Java solution included in Java Standard Edition

.I. n
Web services
Business functionality is decomposed into services

.T ci
The implementation details are hidden; the interface is published
A Web service is the software interface that describes a collection of

.
operations that can be accessed over the network

C
The interface and data transfer are XML

.F a
Providing Web service interfaces for EJBs is a powerful technique

C rm
Common Object Request Broker Architecture (CORBA)
A language-neutral standard
Provides a set of standard object services with APIs
to fo
The Spring Framework
A lightweight alternative to Java EE containers for JavaBeans
ec vo

Copyright IBM Corporation 2008

Figure 1-14. Other distributed component technologies WD352 / VD3521.0

Notes:
oy si

Java Remote Method Invocation is a distributed object model in which the methods of
remote objects written in the Java programming language can be invoked from other Java
u

virtual machines (JVMs), possibly on different hosts connected by a network.


cl

The Object Management Group (OMG) defined the Common Object Request Broker
Architecture (CORBA) before Java was invented. CORBA was designed to allow
applications written in C++ and other object-oriented languages to interoperate. CORBA
Ex

introduces the concept of Object Request Brokers (ORBs) that send information over the
Internet InterOrb protocol (IIOP).
Remote clients can access EJBs using RMI over IIOP, and this is exactly what happens in
pr

WebSphere Application Server. The requirement to provide RMI over IIOP has been part of
the EJB standard since the EJB 2.0 specifications, and earlier EJB implementations
typically used RMI/IIOP anyway.
IIOP allows easy communication between legacy applications written in diverse languages
(C++, Smalltalk, and other CORBA supported languages) with components running on the
Java platform.

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-17


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Notably absent from the list above are the Microsoft proprietary protocols of COM+ and
DCOM. They are based on the based on the component object model (COM) and provide
distributed object technology for the .NET framework.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

1-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

J2EE development pain points

Complexity of business logic programming

.I. n
Complexity and performance of persistence programming
model

.T ci
Presentation layer and logic mix

.
Types, complexity, document model, extension, and

C
performance of Web services

.F a
Multi-member team development

C rm
Lengthy edit-compile-debug cycle These are some of the
issues that Java EE 5
to fo
addresses.
ec vo

Copyright IBM Corporation 2008

Figure 1-15. J2EE development pain points WD352 / VD3521.0

Notes:
oy si

Recall what was discussed earlier that this course uses the term Java Enterprise Edition or
Java EE whenever possible, but the naming convention changed from version 2 (J2EE)
u

and version 5 (Java EE 5).


cl

This diagram discusses the pain points for the enterprise architecture prior to Java EE 5. In
other words, these are some of the issues that had to be dealt with when developing
applications in the J2EE 1.2, J2EE 1.3, and J2EE 1.4 architectures.
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-19


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Component APIs
Web components
Java servlet
Defines servlets, filters, and listeners

.I. n
JavaServer Pages (JSP)
Defines the ways in which markup and Java can be combined to create

.T ci
dynamic pages
Builds on servlet technology

.
JavaServer Pages Standard Tag Library (JSTL)

C
Encapsulates core functionality common to many JSP applications into a

.F a
standard set of markup tags
JavaServer Faces (JSF)

C rm
Provides a user interface framework for Web applications
Includes input validation, event handling, data conversion, and page
navigation
EJB components
to fo
Major changes in Java EE 5 for EJB are the focus of this course.
Web services
Java EE 5 also brings major changes to Web services
ec vo

Copyright IBM Corporation 2008

Figure 1-16. Component APIs WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

1-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Additional APIs used in this course


Java Message Service (JMS)
Allows Java EE application components to create, send, receive, and
read messages

.I. n
Enables distributed communication that is loosely coupled, reliable,

.T ci
and asynchronous
Java Transaction API (JTA)
Provides a standard interface for demarcating transactions

.
Java Persistence API (JPA)

C
.F a
A solution for persistence based on an object-relational mapping
approach

C rm
Defines an API, query language, and mapping metadata
Java Authentication and Authorization Service (JAAS)
Provides a way for a Java EE application to authenticate and
to fo
authorize a specific user or group of users to run it
Java Naming and Directory Interface (JNDI)
Gives applications access to naming and directory services
ec vo

Copyright IBM Corporation 2008

Figure 1-17. Additional APIs used in this course WD352 / VD3521.0

Notes:
oy si

Notes
u

Later lectures in this course look in more detail at JMS, JTA, and JPA.
You can use JMS when working with message-driven beans.
cl

You can use JTA when working with EJB transactions.


Ex

You can use JPA when working with entity beans.


pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-21


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Java Naming and Directory Interface


The Java Naming and Directory Interface (JNDI) is an API for
directory services that allows clients to discover and look up
data and objects by name. The API provides:

.I. n
A mechanism to bind an object to a name
A directory lookup interface that allows general queries

.T ci
An event interface that allows clients to determine when directory
entries have been modified

.
LDAP extensions to support the additional capabilities of an LDAP

C
service

.F a
Java application

JNDI also specifies a service provider JNDI API

C rm
interface (SPI) that allows directory
Naming manager
service implementations to be
plugged into the JNDI SPI
to fo
framework
LDAP

DNS

NIS
...
ec vo

Copyright IBM Corporation 2008

Figure 1-18. Java Naming and Directory Interface WD352 / VD3521.0

Notes:
oy si

JNDI services fall into two general categories:


u

Directory services
Object binding and lookup
cl

Only the latter is of interest in this course.


Ex

Acronyms:
LDAP: Lightweight Directory Access Protocol is a standard interface directory access
DNS: Domain Name Service
pr

NIS: Network Information Service from Sun Microsystems

1-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The role of deployment descriptors


The original motivating concept for deployment descriptors (DD) is
the separation of deployment and development concerns
Creating DD is a major development task itself

.I. n
Development tools usually help generate DD, but cannot do

.T ci
everything
Annotations simplify the task of creating DD
Added to code in a more concise format than XML

.
Deployment tools generate DD from annotations

C
.F a
Annotations provide a convenient override mechanism
If both annotations and DD configure the same thing, the DD

C rm
overrides
Annotations are used
extensively when
building EJBs in this
to fo
course
ec vo

Copyright IBM Corporation 2008

Figure 1-19. The role of deployment descriptors WD352 / VD3521.0

Notes:
oy si

Deployment descriptor files (XML files) where used in earlier versions of Java Enterprise
Edition to help separate development and deployment concerns.
u

In the case of Java EE 5, annotations further simplifies the developer's task. You will be
cl

covering these annotations in a subsequent unit.


Java EE 5 defines a number of types or groups of annotations, defined in a number of Java
Ex

Specification Requests (JSRs).


Java EE 5 defines the following types of annotations:
JSR 250: Common annotations
pr

JSR-220: EJB 3.0 annotations


JSR-181: Web services annotations
JSR-220: Java Persistence API annotations
JSR-222: JaxB annotations

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-23


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JSR-224: WS2 annotations

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

1-24 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Reviewing annotations in Java SE 5


Annotations provide data about a program (that is, metadata)
that is not part of the program itself

.I. n
They have no direct effect on the operation of the code they annotate
Sample uses:

.T ci
Information for the compiler
Annotations can be used by the compiler to control error processing
Compiler-time and deployment-time processing

.
Software tools can process annotation information to generate code,

C
.F a
descriptor files, and so on
Run time processing

C rm
Some annotations are available to be examined at run time
Can be applied to classes, fields, methods, and other program
elements
to fo
Often replaces information that might have been captured in a
comment
ec vo

Copyright IBM Corporation 2008

Figure 1-20. Reviewing annotations in Java SE 5 WD352 / VD3521.0

Notes:
oy si

This slide provides a review of what annotations do. You will recall that annotations were
introduced in Java SE 5.
u

Annotations consist of an at sign (@) followed by an annotation type.


cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-25


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Some built-in Java 5 SE annotations


@Overrides
Applied to a method
Indicates compiler should generate an error if method does not

.I. n
actually override a superclass method

.T ci
@Deprecated
Applied to a method
Indicates the compiler should generate a warning when a method is

.
used externally

C
.F a
@SuppressWarnings
Applied to a type or method

C rm
Indicates the compiler should suppress warnings for that element and
all subelements
@Deprecated
to fo
public void oldMethod() {...}

@SuppressWarnings
public void yesIknowIuseDeprecatedMethods() {...}
ec vo

Copyright IBM Corporation 2008

Figure 1-21. Some built-in Java 5 SE annotations WD352 / VD3521.0

Notes:
oy si

You can use these annotations in any Java SE or EE code. They are defined in package
java.lang, so no import statement is required. You are probably already familiar with these
u

annotations if you have done development in Java 5 SE.


cl

An annotation is a special kind of modifier, which can be used anywhere that other
modifiers (such as public, static, or final) can be used.
Ex
pr

1-26 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Application files are packaged into archives


DD = Deployment Descriptor (*optional in Java EE 5)

Enterprise
DD

.I. n
Application
.ear
Adapters

.T ci
DD
Resource
module Utility
.rar module
.jar

.
DD

C
Classes

.F a
Web
EJB module

C rm
module .war
.jar Client
module
.jar
to fo
Enterprise DD
bean
DD

HTML,
Servlet JSP DD Client
GIF, and
class
so on
ec vo

Copyright IBM Corporation 2008

Figure 1-22. Application files are packaged into archives WD352 / VD3521.0

Notes:
oy si

The various Archive files can:


u

Contain source
Be opened with a zip utility
cl

Many simple applications no longer require deployment descriptors, including:


Ex

EJB applications (.JAR files)


Web applications that use JSP technology only
Application clients
pr

Enterprise applications (.EAR files)


The Java EE specification defines standard archive formats:
Enterprise application
- Packaged in an enterprise archive (.ear) file
- Deployment descriptor: META-INF\application.xml

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-27


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

EJB module
- Contains a set of EJBs
- Packaged in a Java archive (.jar) file
- Deployment descriptor (optional) : META-INF\ejb-jar.xml
Web module

.I. n
- Contains assets that make up a Web application
- Packaged in a Web archive (.war) file

.T ci
- Deployment descriptor: WEB-INF\web.xml
Application client module

.
- Contains the classes and related flies that make up a Java SE application that is a

C
.F a
client to an enterprise application
- Packaged in a Java archive (.jar) file

C rm
- Deployment descriptor: META-INF\application-client.xml
Resource adapter module
- Contains classes and other assets that make up a resource adapter
to fo
- Packaged in a resource adapter archive (.rar) file
This diagram shows a simplified story.
ec vo

WebSphere extensions add more deployment descriptors. The most commonly used
are associated with EJB modules and are called ibm-ejb-jar-ext.xml and
ibm-ejb-jar-bnd.xml.
Web services can add deployment descriptors to EJB, Web, and Utility modules.
oy si
u
cl
Ex
pr

1-28 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java EE application components

Deployment
Enterprise application (EAR) Descriptors
*optional

.I. n
Web module EJB 3.0 module Utility Application

.T ci
(WAR) (JAR) module client module
(JAR) (JAR)
Session
Session

.
HTML Main class
MDB

C
Java beans
MDB

.F a
Java beans
Entity Java
classes

C rm
Servlet or JSP Java beans
Java
classes Java
classes
*Deployment *Deployment *Deployment
descriptor descriptor *Deployment descriptor
descriptor
to fo
Runs in application
Runs in application server client container
ec vo

Copyright IBM Corporation 2008

Figure 1-23. Java EE application components WD352 / VD3521.0

Notes:
oy si

An EJB module contains these elements:


u

One or more deployable enterprise beans.


Optionally, a deployment descriptor, stored in an XML file
cl

An EJB module is installed and run in an enterprise bean container. Packaging options:
Ex

You can package an EJB 3.0 module with an EJB 3.0style session and
message-driven beans exclusively.
You can package an EJB 3.0 module with an EJB 2.1style session and
message-driven beans exclusively.
pr

You can package an EJB 3.0 module with a combination of 2.1 and 3.0style beans.
Note: EJB modules that contain EJB 3.0 beans must be at the EJB 3.0 specification level
when running on the product.

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-29


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

To set the EJB module to support EJB 3.0 beans, you can set the ejb-jar.xml deployment
descriptor level to 3.0, or you can make sure that the module does not contain an
ejb-jar.xml deployment descriptor.
An EJB module can be used as a standalone module, or it can be combined with other
modules to create an enterprise module.
An EJB project must be referenced by an enterprise module project (defined as a module
in an EAR file) ) in order to be deployed successfully and run on a server.

.I. n
Utility modules are used for Java Persistence API (JPA) projects or EJB 2.1 and earlier

.T ci
projects.
Resource archives can be added to an enterprise application archive, but a more common
approach is to install them directly on the application server so that applications can share

.
them. If the RAR is used only by one application, you can add it to the EAR.

C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

1-30 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java EE resource types


Data sources
Used to obtain connections to a relational database
Java Messaging Service (JMS) topics or queues

.I. n
Used to access JMS destinations

.T ci
Other EJBs
Mail

.
Web service

C
Used to access Web service endpoints

.F a
Connection factories for resource adapters

C rm
Environment entries
and so forth
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-24. Java EE resource types WD352 / VD3521.0

Notes:
oy si

Installed applications use a data source to obtain connections to a relational database.


u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-31


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Checkpoint
1. What are annotations?

2. Name the four containers included in Java EE architecture

.I. n
3. Describe what a Java EE data source does

.T ci
4. State what JNDI stands for and give an example of when you
might use it

.
C
.F a
5. What are some of the issues that developers experienced
problems with in earlier Java Enterprise versions (J2EE)?

C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-25. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.

4.
pr

1-32 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Unit summary
Having
Havingcompleted
completedthis thisunit,
unit, you
youshould
shouldbe beable
ableto:
to:
Name
Namethe theeditions
editionsof ofthe
theJava
Javaplatform
platformand
andstate
statehow
howthey
they

.I. n
relate
relateto
toeach
eachother
other
Describe
Describethe themulti-tier
multi-tierarchitecture
architectureof ofJava
JavaEEEE

.T ci
List
Listthe
theservices
servicesand andAPIs
APIsprovided
providedby byJava
JavaEEEEcontainers
containers
Describe some of the issues encountered when
Describe some of the issues encountered when developing developing

.
enterprise
enterpriseapplications
applicationsin inearlier
earlier J2EE
J2EEversions
versions

C
.F a
Explain
Explainthethepurpose
purposeof ofthe
theJava
JavaNaming
Namingand andDirectory
Directory
Interface
Interface(JNDI)
(JNDI)

C rm
Describe
Describehow howJava
JavaEE EEisispackaged
packagedfor for deployment
deployment
Define data sources and resources
Define data sources and resources
to fo
ec vo

Copyright IBM Corporation 2008

Figure 1-26. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 1. Java EE architecture 1-33


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

1-34 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 2. Introduction to EJB 3

What this unit is about


This unit gives an overview of the role of Enterprise JavaBeans (EJBs)
in an enterprise application, explains the rationale for using EJBs, and

.I. n
introduces the types of EJBs defined in the EJB 3.0 specification.

.T ci
What you should be able to do
After completing this unit, you should be able to:

.
C
Define Enterprise JavaBeans

.F a
Explain when a developer should consider using EJBs

C rm
Describe the value proposition of the Java EE 5 and EJB 3.0
specifications
Explain the role of annotations for EJBs
to fo
Describe dependency injection
Define transactions
List the types of EJBs and state the purpose of each
ec vo

How you will check your progress


Checkpoint
oy si

Exercise
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis thisunit,
unit,you
youshould
shouldbe beable
ableto:
to:
Define
DefineEnterprise
EnterpriseJavaBeans
JavaBeans

.I. n
Explain
Explainwhen
whenaadeveloper
developer should
shouldconsider
considerusing
usingEJBs
EJBs
Describe
Describethe thevalue
valueproposition
propositionofofthe
theJava
JavaEE
EE55andandEJB
EJB3.0
3.0

.T ci
specifications
specifications
Explain
Explainthetherole
roleofofannotations
annotationsforforEJBs
EJBs

.
Describe
Describedependency
dependencyinjection
injection

C
.F a
Define
Definetransactions
transactions
List
Listthe
the types
types of
of EJBs
EJBs and
andstate
statethe
thepurpose
purposeofofeach
each

C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

2-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Defining Enterprise JavaBeans


Enterprise JavaBeans (EJB) is a server-side component technology
intended to simplify the process of building enterprise-level, distributed
applications in Java

.I. n
Enterprise beans are standard Java EE components for writing
distributed object systems

.T ci
An enterprise bean is a component that implements EJB technology
Enterprise beans encapsulate the business logic of an application

.
C
.F a
C rm
EJBs
Client
Servlets
to fo
JSPs

Entities
ec vo

Copyright IBM Corporation 2008

Figure 2-2. Defining Enterprise JavaBeans WD352 / VD3521.0

Notes:
oy si

Conceptually, this definition has not changed since the original EJB specification.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

When to use an EJB architecture


Consider using an EJB architecture in these circumstances:
Transactions are required to ensure data integrity
Persistent state management is required

.I. n
The application must be distributable and scaleable

.T ci
The application will use a variety of clients
You require a vendor-neutral enterprise application architecture

.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-3. When to use an EJB architecture WD352 / VD3521.0

Notes:
oy si

Transactions are defined later in the lecture.


u
cl
Ex
pr

2-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Enterprise applications need runtime services


Enterprise applications often depend upon services provided
by the runtime environment (the Java EE application server):
Transaction management

.I. n
Ensuring that groups of related operations are performed as a single
unit of work

.T ci
Security services
Preventing unauthorized access to resources
Persistent-state management

.
A way of storing data permanently

C
.F a
Resource management
Providing better scalability and performance

C rm
Multithreading
Allowing concurrent access to business logic and data

The runtime environment should provide common services


The same set of services should always be available
to fo
A comprehensive set of services should be provided
APIs should be identical on different platforms
ec vo

Copyright IBM Corporation 2008

Figure 2-4. Enterprise applications need runtime services WD352 / VD3521.0

Notes:
oy si

A great benefit of EJB is that developers do not have to write code for these services.
Developers can concentrate on business and application logic.
u

Java EE application servers provide the services mentioned above.


cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Features of Enterprise JavaBeans


Enterprise beans allow remote access
Clients on different systems and different
JVMs can access them

.I. n
Pe
Enterprise beans take advantage of Security rs
services provided by the container in i st

.T ci
en
which they run ce
Standard services include: Clustering

.
Component life cycle

C
Persistence

.F a
Transaction management
Security and authorization

C rm
Servlets Entities n
Infrastructure management JSPs t io
ac
Pooling, clustering, caching,
a ns
and so forth Tr
EJBs
An enterprise bean can be deployed in EISs
to fo
different environments and exhibit
different behaviors without changing its
code
Messaging
ec vo

Copyright IBM Corporation 2008

Figure 2-5. Features of Enterprise JavaBeans WD352 / VD3521.0

Notes:
oy si

These features were also available in earlier versions of enterprise Java.


u
cl
Ex
pr

2-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

A brief history of EJB technology


EJB 1.0 released March 98
Conceptual goals were roughly the same as today
To provide distributable component for business logic

.I. n
Session beans are the only mandatory type of EJB
EJB 1.1 (December 99)

.T ci
All compliant servers must support EJB types for both business logic (session beans)
and persistence (entity beans)
XML-based deployment descriptors allow declarative definition of container services

.
EJB 2.0 (August 01)

C
.F a
Addressed issues of compatibility, interoperability, and performance
Added message-driven beans to support messaging middleware

C rm
EJB 2.1 (November 03)
Added support for Web services
Enhanced EJB Query Language (SQL-like queries)
Java EE 5 introduces EJB 3.0 (May 06)
to fo
Swept away growing complexity of previous releases
Offered the power of enterprise beans without the need
to write much code
Entity beans become plain old Java classes (POJO)
ec vo

Copyright IBM Corporation 2008

Figure 2-6. A brief history of EJB technology WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Java EE 5 and EJB 3.0 value proposition


Simplified business logic development

Simplified testing and dependency management

.I. n
.T ci
Simplified persistence with object-relational mapping (ORM)

Enhanced Web services programming model

.
C
.F a
Java EE 5 released a major update to
EJB specification: EJB 3.0

C rm
Consistent with theme of Java EE5,
EJB 3.0 simplifies development and
to fo
usage experience
ec vo

Copyright IBM Corporation 2008

Figure 2-7. Java EE 5 and EJB 3.0 value proposition WD352 / VD3521.0

Notes:
oy si

Java EE 5 is all about ease of development. The focus is on the ability to develop artifacts
with a simple editor such as Notepad.
u

Plain old Java object (POJO)-based business logic reduces tools dependency. The ability
cl

to use simple metadata annotations, common patterns for references, enables rapid edit
compile and debug cycles. The POJO-based persistence model is modeled on successful
patterns. It simplifies JDBC access patterns and can be integrated with Web services. The
Ex

container stays out of the way. Java EE 5 supplies standardized object-relational mapping
(ORM) metadata that can be then used with any compliant ORM provider.
Web service support includes support for document style, full XML schema support,
pr

progressive disclosure of complexity, and the latest standards support (SOAP 1.2, WSDL
2.0, WS-I BP 1.1, WS-Security).

2-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Key themes of the EJB 3.0 specification


Simplified business logic development:
Plain old Java object (POJO)-based programming model
No need to extend specific classes or implement specific interfaces

.I. n
Highly leverages J2SE 5.0 annotations

.T ci
Pervasive use of default values throughout the entire programming
model
Aspect-oriented interceptor model enables non-invasive decoration of

.
behaviors

C
.F a
Simplified testing and inter-component assembly:
POJO model enables testing outside the container

C rm
Inter-component linkages expressed through popular Inversion of
Control (IoC) concepts such as resource injection
to fo
ents
context.look
up(home) implem ean
catch(RemoteException e) B
Session
ec vo

Copyright IBM Corporation 2008

Figure 2-8. Key themes of the EJB 3.0 specification WD352 / VD3521.0

Notes:
oy si

This slide is intended to show how the EJB 3.0 specification does away with some of the
convoluted logic of earlier EJB specifications.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Key themes of the JPA specification


Simplified persistence based on Java Persistence API (JPA)
specification
Replaces entity EJB from earlier versions

.I. n
JPA was developed as part of JSR-220 (Enterprise JavaBeans

.T ci
3.0)
POJO-based persistence entity beans
No need to extend specific classes or implement specific interfaces

.
Modeled on successful industry patterns

C
.F a
Highly leverages J2SE 5.0 annotations
Supports usage in both in Java EE and Java SE environments

C rm
to fo
new() persist() read
POJO Entity
Application manager RDB
update
ec vo

Copyright IBM Corporation 2008

Figure 2-9. Key themes of the JPA specification WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

2-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Annotations
The most prominent new feature in EJB 3.0 is the use of annotations
Simplifies EJB development
Removes the need for deployment descriptor for most purposes

.I. n
Annotations are metadata which can be embedded directly into the
Java classes they describe.

.T ci
Remove the need for marker interfaces (like java.rmi.Remote)
Allow application settings to be visible in the component they affect

.
The server generates EJB infrastructure code based on annotations

C
A minimum of annotations are mandatory because well-chosen defaults are

.F a
used when no annotation is provided

C rm
A combination of annotations and deployment descriptor can be used.
The deployment descriptor augments or overrides the annotations
Allows for customization when application is assembled or deployed
to fo
@Stateful
public class ReserverImpl implements Reserver {
@EJB Borrower borrower;
...
ec vo

Copyright IBM Corporation 2008

Figure 2-10. Annotations WD352 / VD3521.0

Notes:
oy si

EJB 3.0 uses metadata annotations, that are part of Java SE 5.0.
u

Annotations are similar to XDoclet, a powerful open-source framework extensible,


metadata-driven, attribute-oriented framework that is used to generate Java code or XML
cl

deployment descriptors.
Annotations can be used by the compiler to generate boilerplate code.
Ex

Java EE 5 provides annotations for the following tasks, among others:


Defining and using Web services
Developing EJB software applications
pr

Mapping Java technology classes to XML


Mapping Java technology classes to databases
Mapping methods to operations
Specifying external dependencies

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-11


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Specifying deployment information, including security attributes


Earlier EJB specifications allowed only the declarative approach. Deployment descriptors
were mandatory. Unless tools generated them, creating them was a significant
development task. The introduction of annotations that can specify most deployment
descriptor information greatly simplifies the process of developing EJBs.
Use of annotations and predefined defaults for omitted values can make development of
EJBs look deceptively simple. You do need to understand the complexities of the EJB

.I. n
specification to set non-default properties in many of the situations that arise in real-work

.T ci
enterprise applications.

.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

2-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

EJB 3.0 configuration defaults


EJB 3.0 specifies defaults to reduce the need for the developer
to specify common, expected behaviors and requirements on
the EJB container

.I. n
These are applied when the relevant annotations or deployment

.T ci
descriptor elements are missing

Defaults include

.
JNDI bindings for business interfaces

C
.F a
Exception handling:
All checked exceptions except java.rmi.RemoteException are

C rm
assumed to be application exceptions and passed to the caller
All exceptions that inherit from either java.rmi.RemoteException
or java.lang.RuntimeException are assumed to be system
exceptions
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-11. EJB 3.0 configuration defaults WD352 / VD3521.0

Notes:
oy si

Exceptions that inherit from java.lang.RuntimeException are unchecked. In EJB, an


application exception is an exception that the client is expected to handle. All checked
u

exceptions are assumed to be application exceptions. When thrown, such exceptions are
cl

passed directly to the method invoker. In EJB, it is not assumed that system exceptions are
expected by the client. When encountered, such exceptions are not passed to the client as
is but are wrapped in a javax.ejb.EJBException instead.
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-13


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Simplified resource access: Dependency injection


In the dependency injection pattern, an external entity
automatically supplies the dependencies of an object

.I. n
The object need not request these resources explicitly

In Java EE 5, dependency injection can be applied to all

.T ci
resources that a component needs
Creation and lookup of resources are hidden from application code

.
C
Dependency injection can be applied throughout Java EE 5

.F a
technology

C rm
EJB containers
Servlet EJB
Web containers JNDI lookup
Clients
to fo
Web services
EJB Servlet
injected
ec vo

Copyright IBM Corporation 2008

Figure 2-12. Simplified resource access: Dependency injection WD352 / VD3521.0

Notes:
oy si

The new specification introduces a powerful mechanism for obtaining Java EE resources
(JDBC data source, JMS factories and queues, and EJB references) and to inject them into
u

EJBs, entities, or EJB clients.


cl

In EJB 2.x, the only way to obtain these resources was to use JNDI lookup using resource
references, with a piece of code that could become cumbersome and vendor specific.
Ex

EJB 3.0 adopts a dependency injection (DI) pattern, which is based on annotations or XML
descriptor entries, and it allows you to inject dependencies on fields or setter methods.
The figure in the slide shows two scenarios:
1. An servlet performing an traditional JNDI look-up of an EJB
pr

2. An EJB being injected into the EJB through resource dependency injection.

2-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Example of resource injection


In this example, the @Resource annotation specifies a JMS connection factory and
queue for use by a bean that uses the JMS API to send a message
The name parameter specifies the JNDI name configured on the server

.I. n
@Stateless
public class ReturnerImpl implements Returner {
@Resource(name = "jms/libraryCFRef")

.T ci
private ConnectionFactory connectionFactory;
@Resource(name = "jms/libraryQueueRef")
private Queue queue;

.
For resources configured on the server, the annotation injects resource references.

C
.F a
To bind the reference to the resource, use the appropriate deployment descriptor
JMS resources are bound in the WebSphere bindings deployment descriptor ibm-ejb-bnd.xml

C rm
<ejb-jar-bnd >

<session name="ReturnerImpl">
<resource-ref name="jms/libraryCFRef"
binding-name="jms/libraryCF">
to fo
</resource-ref>
<message-destination-ref name="jms/libraryQueueRef"
binding-name="jms/libraryQueue" />
</session>
</ejb-jar-bnd>
ec vo

Copyright IBM Corporation 2008

Figure 2-13. Example of resource injection WD352 / VD3521.0

Notes:
oy si

This example show how to use the @Resource annotation to inject resource references
such into EJBs. It is taken from the library case study that you build in the exercises of this
u

course.
cl

For a data source you are more likely to use entity beans, and not inject use the data
source directly in your beans.
Ex

Resources provided by Java EE, such as EJBContext its subtypes SessionContext and
MessageDrivenContext and can be injected directly. There is no resource reference.
The @Resource annotation can take the following attributes:
authentication: The authentication type of this resource must
pr

Resource.AuthenticationType.APPLICATION or
Resource.AuthenticationType.CONTAINER
description: Descriptive text
mappedName: A product specific name that the resource is mapped to .

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-15


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

name: The name of the resource.


sharable: True or false indicates whether the resource can be shared among components
type: the Java type of the resource

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

2-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Using annotations for injection


Dependency injection:
Hides creation and lookup of resources from application code
Clients that are managed classes can access EJBs by declaring a

.I. n
dependency:
@EJB

.T ci
LoanManager loanManager;

.
Resource injection:

C
Lets EJBs access resources after declaring them

.F a
@Resource

C rm
EJBContext ec;
Injectable resources include:
SessionContext subtype of EJBContext
MessageDrivenContext subtype of EJBContext
to fo
TimerServer obtained from EJBContext
UserTransaction obtained from EJBContext
EntityManager obtained from persistence context
And more
ec vo

Copyright IBM Corporation 2008

Figure 2-14. Using annotations for injection WD352 / VD3521.0

Notes:
oy si

Dependency injection is used to hide resource creation and lookup from application code.
u

Use the @EJB annotation to reference business interfaces of EJBs and home interfaces
for EJBs built to earlier specifications.
cl

Use @WebServiceRef to reference Web services.


The old way of locating and accessing EJBs, using the Java Naming and Directory
Ex

Interface (JNDI), is still available as an alternative to dependency injections.


pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-17


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Requesting container services


Developers can request container services by:
Using Annotations: add annotations to the Java code for an EJB

.I. n
@TransactionManagement(TransactionManagementType.CONTAINER)
public class PatronManagerImpl implements PatronManager

.T ci
Declaratively: provide an XML deployment descriptor file separate
from Java code

.
C
Programmatically: call API for selected services

.F a
Requires access to the EJB context

C rm
A combination of annotations and deployment descriptor:
The deployment descriptor augments or overrides the annotations
Allows for customization when application is assembled or deployed
to fo
As much as possible, the EJB specification sets defaults that
satisfy the most common situations.
ec vo

Copyright IBM Corporation 2008

Figure 2-15. Requesting container services WD352 / VD3521.0

Notes:
oy si

Earlier EJB specifications allowed only the declarative approach. Deployment descriptors
were mandatory. Unless tools generated them, creating them was a significant
u

development task. The introduction of annotations that can specify most deployment
cl

descriptor information greatly simplifies the process of developing EJBs.


The annotation example above states the default explicitly: by default the EJB container
runs each EJB method in a transactional context. The deployment descriptor equivalent for
Ex

the EJB annotation shown in the figure is:


<transaction-type>CONTAINER</transaction-type>
The programmatic approach is listed above for completeness only. The main distinction is
pr

between injection using annotations and declaration using deployment descriptors.

2-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Transactions are logical units of work


Commit: Actions considered to be a group must all complete
successfully
Roll back: If any one action fails, the original state (before the

.I. n
actions were executed) must be restored

.T ci
TRANSACTION
success success success

.
Action 1 Action 2 Action 3

C
.F a
C rm
TRANSACTION
success success failure
Action 1 Action 2 Action 3
to fo
undo action 1 undo action 2 undo action 3
ec vo

Copyright IBM Corporation 2008

Figure 2-16. Transactions are logical units of work WD352 / VD3521.0

Notes:
oy si

Recall that one of the reasons for using EJBs is to get transactional support.
u

This slide describes what transactions are.


The set of actions or activities within a transaction are also referred to as a logical unit of
cl

work (UOW). Transactions ensure that the UOW succeeds as a whole (that is, it is atomic)
or all the activities within UOW are rolled back.
Ex

A transaction is unit of activity, within which multiple updates to resources can be made
atomic (as an indivisible unit of work) such that all or none of the updates are made
permanent. For example, during the processing of an SQL COMMIT statement, the
database manager atomically commits multiple SQL statements to a relational database. In
pr

this case, the transaction is contained entirely within the database manager and can be
thought of as a resource manager local transaction (RMLT).
If a transaction involves multiple resource managers, for example multiple database
managers, an external transaction manager is required to coordinate the individual

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-19


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

resource managers. A transaction that spans multiple resource managers is referred to as


a global transaction.
If an application uses only one RMLT, atomic behavior can be guaranteed by the resource
manager, which can be accessed in a local transaction containment (LTC) context.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

2-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The ACID properties


A transaction has the following characteristics:

.I. n
Atomic: Indivisible, all or nothing

.T ci
Consistent: Effects of a transaction preserve invariant properties
For example:
quantity in stock + quantity sold = constant

.
C
.F a
Isolated: Intermediate states are not transparent to other
transactions; transactions appear to execute serially

C rm
Involved objects may not be altered by another transaction

Durable: Effects of a completed transaction are persistent and never


lost
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-17. The ACID properties WD352 / VD3521.0

Notes:
oy si

The property of atomicity guarantees that the set of operations will occur as an
all-or-nothing proposition. The transaction will not leave any work partially completed. If the
u

transaction cannot complete all the work, then any work it could complete will be undone,
cl

leaving the system as if the transaction had never been attempted.


The property of consistency guarantees that, if you correctly implement a transaction,
the system will leave data in a consistent state. Note that this does not mean that the
Ex

transaction can guarantee accuracy. If you implement a transfer incorrectly so that it


deposits to (or deducts from) both accounts, your data is going to end up inconsistent.
The transaction system does not know the semantics of your application. But as long as
pr

your code does the right thing, the before and after states of the data will be consistent.
The property of isolation guarantees that in-flight transactions will be property protected
from each other, even if they are running in parallel. In other words, one transaction will not
be allowed to see the working state of another's data. This is important because otherwise,
one transaction could make a decision based on a change that was later rolled back.
Concurrent transactions must run as if they are the only ones.

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-21


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The property of durability guarantees that, once a transaction has successfully


completed its work, the effects of that work will not be lost. In other words, it will be possible
for you to re-create the data if it is modified (by a transaction that later aborts) or lost (due to
something like a media failure).

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

2-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Transaction example
Funds transferred between bank accounts

.I. n
update
Client Account

.T ci
table
Object 1
transfer(acc1,
acc2,amt)

.
withdraw(amt)

C
.F a
Transfer
Object

C rm
deposit(amt)
Account
Object 2 update
to fo
table
ec vo

Copyright IBM Corporation 2008

Figure 2-18. Transaction example WD352 / VD3521.0

Notes:
oy si

The client initiates the transaction by requesting a transfer of funds between accounts.
Work through this considering how the ACID properties help maintain reliable data:
u

A: If any part of the operation fails, the whole transaction is rolled back.
cl

- For example, a database update fails, or Account Object 1 detects insufficient funds.
C: At the end of the transaction, invariant properties are preserved.
Ex

- The sum of the account balances remains constant.


I: The objects cannot be used by another transaction while the transfer is under way.
- The transfer object, the account objects, and any accessed data stores are locked.
pr

D: The effects of the transaction are persistent.


- The updated balances are written to the data store.

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-23


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Transaction definitions
Transactional object
An object that is invoked within a transaction
Can only be associated with one transaction at a time

.I. n
EJBs may be transactional objects

.T ci
Transactional client
A program that invokes methods on transactional objects

.
Transaction manager

C
.F a
An application server service that coordinates transaction processing

C rm
Resource manager
Manages the transaction for a specific type of resource
Examples: Relational Database Manager (RDBM), JMS message
providers, Enterprise information systems (EIS)
to fo
Transactional context
Information that is shared by transaction participants to ensure the
transaction semantics
ec vo

Copyright IBM Corporation 2008

Figure 2-19. Transaction definitions WD352 / VD3521.0

Notes:
oy si

EJBs are transactional by default: unless you override the default settings, all methods of
EJBs run in a transactional context.
u

Transactional contexts enable participants to associate with a transaction. They also


cl

support the transaction semantics by allowing for coordinated commit or rollback of the
transaction. By default, transactional context is automatically propagated to transactional
objects as they are used. For example, one EJB method calls another EJB method. You
Ex

can use transaction settings to override this.


Resource managers manage transaction semantics for a specific type of resource. The
resource can be any record in a relational database or a queue in messaging system.
pr

Conceptual flow of transactional processing:


A transactional client invokes a method on a transactional object. For example, a
servlet calls a method on an EJB component.

2-24 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty The EJB container informs the transaction manager that a new transaction is required.
The transaction manager creates a transaction context and associates it with the
current thread.
The transactional object performs its work. Work may use multiple transactional
resources. Each resource has been registered with the transaction manager so that
updates can be coordinated.
The method on the original transactional object (EJB component) completes.

.I. n
The transaction manager communicates with the resource managers to commit the

.T ci
transaction, negotiating the outcome with all the involved resource managers. If the
transaction is successful, the method completes, and may return values to the client. If
the transaction fails, the transaction manager coordinates a transaction rollback, and

.
may throw an exception to the client.

C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-25


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Default transaction demarcation with EJBs


By default, when a client calls an client EJB_1 EJB_2
EJB method:

.I. n
If no transaction is started, the EJB call methodA call methodB
container starts one and then
A B

.T ci
transfers control to the method. return
If a transaction is open, the EJB call methodC
calls the method in the existing

.
C
transactional context

C
return

.F a
Each EJB method call potentially return

demarks the start of a

C rm
call methodD
transactional context and a
normal or exception return D
demarks closes the transactional return
to fo
context.
Transactions are propagated
from method to method
ec vo

Copyright IBM Corporation 2008

Figure 2-20. Default transaction demarcation with EJBs WD352 / VD3521.0

Notes:
oy si

If you do nothing in the EJB classes, each EJB method requires a transactional context. If
none is open when the method is called, the EJB container automatically creates one. The
u

EJB container closes the transactional context when the method ends. Typically but not
cl

always, normal return commits the transaction and throwing an exception causes rollback.
In the diagram above, time runs from top to bottom and the call chain runs from left to right.
The vertical gray boxes are methods and the green shaded areas show transactional
Ex

contexts. Thus:
Method A in EJB_1 and method B and C in EJB_2 run in one transaction, and method
D in EJB_2 runs in a second transaction.
pr

You can specify the following by adding annotations to the EJB classes:
Whether to let the EJB or the container manages transactions (The default is container.)
For each method, is a transactional context required? If yes must it be pre-existing in
the calling code, must it be new for this method, or can it be either a pre-existing or new.
(The default is the last option.)

2-26 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Is a transaction context optional or not allowed?

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-27


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Types of EJB 3 beans

Enterprise

.I. n
JavaBeans

.T ci
.
Session Message-

C
.F a
beans driven
beans

C rm
Stateless Stateful
to fo
@Stateless @Stateful @MessageDriven
ec vo

Copyright IBM Corporation 2008

Figure 2-21. Types of EJB 3 beans WD352 / VD3521.0

Notes:
oy si

Anyone who has worked with an earlier EJB specification should notice that there are now
only two main types of EJB, whereas previously there were three. Entity beans are no
u

longer EJBs: they are ordinary JavaBeans.


cl

The annotation before the class declaration determines the type of the EJB.
Session beans contain methods that provide business functionality or provide interfaces to
Ex

the layers of code in the application. Some session beans can hold state information, but
the most commonly used type is stateless.
Message-driven beans (MDBs) are much more specialized. They receive messages from
messaging middleware that is a configured resource on the server. Messages arrive
pr

asynchronously, so these beans are entry points into the application.


The session bean and message driven bean interfaces both extend the
javax.ejb.EnterpriseBean interface.

2-28 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint
1. What are some of the common services provided by the EJB
container?

.I. n
2. What is dependency injection?

.T ci
3. Name three kinds of enterprise beans in EJB 3.0

.
C
4. How does EJB 3.0 simplify the programming model for

.F a
session EJBs?

C rm
5. Name the ACID properties and state what, together, do they
achieve?
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-22. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write down your answers here:


u

1.
cl

2.
Ex

3.
pr

Copyright IBM Corp. 2008 Unit 2. Introduction to EJB 3 2-29


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis thisunit,
unit,you
youshould
shouldbe beable
ableto:
to:
Define
DefineEnterprise
EnterpriseJavaBeans
JavaBeans

.I. n
Explain
Explainwhen
whenaadeveloper
developer should
shouldconsider
considerusing
usingEJBs
EJBs
Describe
Describethe thevalue
valueproposition
propositionofofthe
theJava
JavaEE
EE55andandEJB
EJB3.0
3.0

.T ci
specifications
specifications
Explain
Explainthetherole
roleofofannotations
annotationsforforEJBs
EJBs

.
Describe
Describedependency
dependencyinjection
injection

C
.F a
Define
Definetransactions
transactions
List
Listthe
the types
types of
of EJBs
EJBs and
andstate
statethe
thepurpose
purposeofofeach
each

C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 2-23. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

2-30 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 3. Session EJBs

What this unit is about


This unit describes the most commonly used type of EJBs: session
beans. It explains their purpose and implementation, and compares

.I. n
the two kinds of session EJBs: stateful and stateless.

.T ci
What you should be able to do
After completing this unit, you should be able to:

.
C
Define session beans

.F a
List reasons for using session beans

C rm
Create session bean classes and interfaces
Access session beans from client code
Use the session context to interact with container-managed
to fo
resources
Use annotations with session beans
Describe application bindings for session beans
ec vo

Explain the life cycle of session beans and use life cycle call back
methods
Compare stateful and stateless session beans
oy si

How you will check your progress


u

Checkpoint
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis thisunit,
unit,you
youshould
shouldbe beable
ableto:
to:
Define
Definesession
sessionbeans
beans

.I. n
List
Listreasons
reasonsfor forusing
usingsession
sessionbeans
beans
Create
Createsession
sessionbeanbeanclasses
classesandandinterfaces
interfaces

.T ci
Access
Accesssession
sessionbeans
beansfrom
fromclient
clientcode
code
Use
Use the session context to interactwith
the session context to interact withcontainer-managed
container-managed

.
resources
resources

C
.F a
Use
Useannotations
annotationswithwithsession
sessionbeans
beans
Describe
Describeapplication
applicationbindings
bindingsfor forsession
sessionbeans
beans

C rm
Explain
Explainthethelife
lifecycle
cycleof
ofsession
sessionbeans
beansand anduse
uselife
lifecycle
cyclecall
call
back methods
back methods
Compare
Comparestateful
statefuland
andstateless
statelesssession
sessionbeans
beans
to fo
ec vo

Copyright IBM Corporation 2008

Figure 3-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

3-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Session beans are general-purpose workers


A session bean instance acts on behalf
of a client inside the application server Client
The client invokes the session bean

.I. n
methods
doIt(1)
The session bean performs work for its

.T ci
doIt(2)
client, shielding the client from complexity
by executing business tasks inside the

.
server Session

C
bean

.F a
Session
A session bean is not: bean
Shared while associated with a client

C rm
Session
Persistent bean Pool

The container can maintain a pool of EJB container


to fo
session beans for reuse by any client
ec vo

Copyright IBM Corporation 2008

Figure 3-2. Session beans are general-purpose workers WD352 / VD3521.0

Notes:
oy si

Session beans are the workhorses of enterprise applications. That is to say, they are the
most commonly used EJB type.
u

A session bean:
cl

Has methods that perform work for its client


Gives the client access to functionality located on the server
Ex

Shields the client from complexity of executing business tasks inside the server
Acts on behalf of one client at a time
Is not persistent
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Session beans can have state


Stateless session beans
A stateless session bean does Web container
not maintain a conversational

.I. n
state with the client Servlet
The state of a stateless bean http

.T ci
between method calls is https
provider-dependent Thin
client
The container may reuse, re-create, Session

.
or pool the beans bean

C
Stateful session beans

.F a
In a stateful session bean, instance Session
variables should represent state for bean

C rm
RMI/
a single client IIOP

Because the client interacts with Fat EJB container


the bean to exchange information, client
the state is often called conversational state
to fo
Conversational state can be
maintained over multiple method calls
ec vo

Copyright IBM Corporation 2008

Figure 3-3. Session beans can have state WD352 / VD3521.0

Notes:
oy si

Session beans can be:


u

Stateless
Every call is independent
cl

Stateful
Ex

Holds conversational state between calls.


pr

3-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Reasons to use session beans


The EJB container can manage complex transactions
Transaction boundaries are the methods of the session bean
Your session bean methods can call other bean methods that

.I. n
participate in the same transaction

.T ci
BeanA BeanB BeanC
methodA methodB methodC

.
Can be one transaction

C
Local or remote access is transparent: business logic is the

.F a
same regardless of whether the client is in the same JVM

C rm
The EJB container can provide secure access
Integrated with Java EE security
User credentials from a Web application can be propagated to calls of
to fo
session bean methods
Method access can be restricted declaratively or with annotations
based on caller identity
ec vo

Copyright IBM Corporation 2008

Figure 3-4. Reasons to use session beans WD352 / VD3521.0

Notes:
oy si

Transactions are discussed in more detail in a later unit.


u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

EJB clients: Using EJBs


EJB clients access session beans through the methods
defined in the business interface of the bean

.I. n
Defines the client view of the bean
All other aspects of the bean are hidden from clients

.T ci
Session beans can have more than one business interface
Each client accesses a session bean through one of its interfaces

.
C
.F a
Session beans support three types of client access:
Remote

C rm
Local
AccountBean
Web service debit();
Account
credit();
debit();
to fo
connect();
credit();
encode();
INTERFACE ...
ec vo

Copyright IBM Corporation 2008

Figure 3-5. EJB clients: Using EJBs WD352 / VD3521.0

Notes:
oy si

The business interface of a session bean is an ordinary Java interface that contains the
business methods for a bean.
u

If a bean class has more than one interface then any business interface of the bean class
cl

must be explicitly designated by means of the Local or Remote annotation on the bean
class, or by means of the deployment descriptor.
Ex
pr

3-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Session beans have two parts


The business interface
Defines methods available to the client
A session bean may have one or more interfaces

.I. n
Annotation on the interface specifies availability

.T ci
@Remote Available to clients in remote JVMs
@Local Available only to clients in the same JVM
(stateless only)

.
@WebService Exposes the bean as a Web service endpoint

C
.F a
AccountBean
debit();

C rm
Account
credit();
The bean class debit();
connect();
credit();
Provides the encode();
INTERFACE ...
implementation
to fo
Annotation determines
bean type and, optionally, JNDI name
@Stateless(name="")
@Stateful(name="")
ec vo

Copyright IBM Corporation 2008

Figure 3-6. Session beans have two parts WD352 / VD3521.0

Notes:
oy si

The methods implemented in the bean class must correspond to the business methods
declared in the remote or local business interfaces. They are matched up based on the
u

convention that they have the same name and method signature. Other methods in the
cl

bean class that do not have the corresponding declaration in the business interfaces will be
private to the bean class methods.
If the name of an attribute is omitted from @Stateful or @Stateless, the implementation
Ex

sets the JNDI name. In WebSphere that is the fully qualified interface name. The optional
attributes on the @Stateless and @Stateful annotations are:
name = the name of the EJB in the JNDI context
pr

mappedName = provider-specific name to which the EJB reference is mapped


description = descriptive text

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Remote clients
A remote client of an enterprise bean can run on a different
system and a different Java virtual machine (JVM) from that of
its target bean

.I. n
To the remote client, the location of the enterprise bean is transparent

.T ci
To create an enterprise bean that allows remote access, do
one of the following:

.
Decorate the business interface of the enterprise bean with the

C
@Remote annotation:

.F a
@Remote

C rm
public interface InterfaceName { ... }

Decorate the bean class with @Remote, specifying the business


interface or interfaces:
to fo
@Stateless
@Remote(InterfaceName.class)
public class BeanName implements InterfaceName { ... }
ec vo

Copyright IBM Corporation 2008

Figure 3-7. Remote clients WD352 / VD3521.0

Notes:
oy si

Coding both the interface and the bean class is optional, because the container has all the
information it needs to generate the interface in the bean class. The second example is of a
u

class for which the interface is generated. The generally accepted recommended practice
cl

is to define the interface explicitly.


For the EJB 3.0 level, the WebSphere Application Server runtime provides two distinct
namespaces for EJB interfaces, depending on whether the interface is local or remote. The
Ex

two namespaces are as follows:


JVM-scoped ejblocal: namespace
Global JNDI namespace
pr

Local EJB interfaces and homes must always be bound into a JVM-scoped ejblocal:
namespace; they are accessible only from within the same application server process.
In contrast, remote EJB interfaces and homes must always be bound into the
globally-scoped WebSphere JNDI namespace; they can be accessed from anywhere,
including other server processes and other remote clients. Local interfaces cannot be

3-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty bound into the globally-scoped JNDI namespace, nor can remote interfaces be bound into
the JVM-scoped ejblocal: namespace.
The ejblocal: and globally-scoped JNDI namespaces are completely separate and distinct.
For example, an EJB local interface bound at "ejblocal:AccountHome" is a not at all the
same as a remote interface bound at "AccountHome" in the globally-scoped namespace.
This helps maintain the distinction between your local and remote interface references.
Having a JVM-scoped local namespace also makes it possible for your applications to

.I. n
directly look up or reference local EJB interfaces from anywhere in the JVM server process,
including across Java Platform, Enterprise Edition (Java EE) application boundaries.

.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Local clients
A local client of an enterprise bean runs in the same JVM as
its target bean
By default, undecorated beans are local

.I. n
To create an enterprise bean that explicitly allows only local

.T ci
access, do one of the following:
Decorate the business interface of the enterprise bean with the
@Local annotation:

.
C
.F a
@Local
public interface InterfaceName { ... }

C rm
Decorate the bean class with @Local, specifying the business
interface or interfaces:
to fo
@Local(InterfaceName.class)
public class BeanName implements InterfaceName { ... }
ec vo

Copyright IBM Corporation 2008

Figure 3-8. Local clients WD352 / VD3521.0

Notes:
oy si

Coding both the interface and the bean class is optional, because the container has all the
information it needs to generate the interface in the bean class. The second example is of a
u

class for which the interface is generated. The generally accepted recommended practice
cl

is to define the interface explicitly.


Ex
pr

3-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Example: Stateless session bean with remote interface


@Stateless
@Stateless
public
public class
class TempConverterBean
TempConverterBean implements
implements TempConverter
TempConverter {{

.I. n
public
public float
float cToF(float
cToF(float c)
c) {{
return
return 1.8f*c
1.8f*c ++ 32f;

.T ci
32f;
}}

.
public
public float
float fToC(float
fToC(float f)
f) {{

C
return
return (f-32f)/1.8f;
(f-32f)/1.8f;

.F a
}}
}}

C rm
@Remote
public interface TempConverter
{
public float cToF(float c);
to fo
public float fToC(float f);
}
ec vo

Copyright IBM Corporation 2008

Figure 3-9. Example: Stateless session bean with remote interface WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-11


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Client access to session beans


Java clients that are managed classes can use dependency
injection with the @EJB annotation.
@EJB (name="", beanInterface="", beanName="")

.I. n
public class MyClass { When the annotation has

.T ci
no attributes, default
@EJB values apply.
Account account;
public deposit(double amount) {

.
account.credit(amount);

C
.F a
}
}

C rm
Classes managed by the container include:
Java classes in client container
EJBs
to fo
Servlets, JavaServer Pages, servlet filters, event handlers

Other clients must use JNDI lookup


ec vo

Copyright IBM Corporation 2008

Figure 3-10. Client access to session beans WD352 / VD3521.0

Notes:
oy si

If a stateless session bean uses dependency injection mechanisms for the acquisition of
references to objects in its environment, the container injects these references before any
u

business methods are invoked on the bean instance.


cl

If none of the attributes are specified on the @EJB annotation, default values are applied.
In this case the object reference account is mapped to the Account business interface,
which can be a local or remote interface, depending on the annotation supplied on the
Ex

interface.
The optional attributes on the @EJB annotation are:
name = the name of the EJB reference in the JNDI context
pr

beanName = the name of the EJB to which the reference is mapped


beanInterface = one of the interfaces of the target EJB
mappedName = provider-specific name to which the EJB reference is mapped

3-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The EJB context


Requesting container services means interacting with the
underlying container
javax.ejb.EJBContext is an interface that gives programmatic

.I. n
access to container services for:

.T ci
Security
getCallerPrincipal() EJBContext
isCallerInRole()

.
Transactions

C
getRollbackOnly()

.F a
setRollbackOnly() SessionContext MessageDrivenContext
getUserTransaction()

C rm
EJB timer service
getTimerService()
EJB
getEJBHome()
getEJBLocalHome()
to fo
Use @Resource to inject the context into an EJB:
@Resource
SessionContext context;
ec vo

Copyright IBM Corporation 2008

Figure 3-11. The EJB context WD352 / VD3521.0

Notes:
oy si

The bean may gain access to references to resources and other environment entries in its
context by having the container supply it with those references.
u

Alternatively, the lookup method added to the javax.ejb.EJBContext interface or the JNDI
cl

APIs may be used to look up resources in the bean's environment.


SessionContext and MessageDrivenContext are interfaces that extend EJBContext for use
Ex

in session beans and message-driven beans, respectively.


The bean interacts with the container through SessionContext in order to:
get security credentials
pr

get and set transactional attributes


get timer services
retrieve home interfaces
Later units in this course discuss the sample methods listed above, all of which are defined
in EJBContext.

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-13


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The names EJBHome and EJBLocalHome are legacy from earlier EJB specifications when
EJBs had home interfaces. They still exist internally, and you may need to use the home
interface when using both EJB 2 beans and EJB 3 in one application.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

3-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Rules for writing session beans


A session bean:
Must have at least one business interface
Implements an interface that gives the client view of the bean

.I. n
.T ci
The container must be able to manipulate a session bean
Must be concrete, not abstract or final
Must have a no-argument constructor

.
C
Session bean classes can subclass other classes, including

.F a
other session beans

C rm
Business methods and life cycle callback methods may be defined
either in the bean class or in a superclass

Business method names must not start with ejb


to fo
ec vo

Copyright IBM Corporation 2008

Figure 3-12. Rules for writing session beans WD352 / VD3521.0

Notes:
oy si

Naming conventions, not rules, are to:


u

- Give the interface a mnemonic name with no special prefix or suffix.


- For the class name, append Bean to the interface name.
cl

- Another common convention is to use the suffix Impl on the bean.


Ex

Thus, a bean that performs credit checks may have an interface named CreditChecker and
bean class named CreditCheckerBean.
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-15


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Application bindings
Before an application that is installed on an application server
can start, all EJB references and resource references defined

.I. n
in the application must be bound to the actual artifacts
(enterprise beans or resources) defined in the application

.T ci
server
Refer to EJBs and resources that are configured on the

.
application server by their JNDI names

C
.F a
Use the WebSphere bindings file, ibm-ejb-bnd.xml, to associate
resource references to actual resources

C rm
For EJB 3.0 modules, you do not need to specify JNDI names
to identify EJBs
If you do not explicitly assign bindings, the EJB container assigns
to fo
default bindings
ec vo

Copyright IBM Corporation 2008

Figure 3-13. Application bindings WD352 / VD3521.0

Notes:
oy si

Before an application that is installed on an application server can start, all enterprise bean
(EJB) references and resource references defined in the application must be bound to the
u

actual artifacts (enterprise beans or resources) defined in the application server.


cl

you specify Java Naming and Directory Interface (JNDI) names for the artifacts referenced
in an application.
Ex
pr

3-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

WebSphere default bindings for bean interfaces


WebSphere assigns default names based on patterns:

.I. n
Description Binding pattern

.T ci
Short form local ejblocal:<package.qualified.interface>
interfaces

.
Short form remote <package.qualified.interface>

C
.F a
interfaces

Long form local ejblocal:<component-id>#<package.qualified.interface>

C rm
interfaces

Long form remote ejb/component-id># <package.qualified.interface>


interfaces
to fo
ec vo

Copyright IBM Corporation 2008

Figure 3-14. WebSphere default bindings for bean interfaces WD352 / VD3521.0

Notes:
oy si

You need to know these default bindings to write a client that uses JNDI lookup rather than
dependency injection to access an EJB.
u

NOTE: The component-id defaults to <application-name>/<module-jar-name>


cl

/<ejb-name> unless it is overridden in the EJB module binding file using the component-id
attribute.
Ex

For example, a remote interface's short and long default bindings might be
"com.mycompany.AccountService" and
ejb/AccountApp/module1.jar/ServiceBean#com.mycompany.AccountService",
respectively.
pr

The "long" default bindings for remote interfaces follow recommended Java EE practices in
that they are grouped under an ejb context name.
All local default bindings, both short and long, are placed in the ejblocal:
server/JVM-scoped namespace, while remote default bindings are placed in the server's

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-17


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

root context of the globally-scoped namespace if they are short, or in the <server_root>/ejb
context (just below the server's root context) if they are long.
For more information, see section EJB 3.0 application bindings overview in the WebSphere
Application Server V7.0 Information Center at
http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

3-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Stateful session beans


Sometimes you need the server side to remember
information between method calls

.I. n
In a stateful session bean, instance variables represent the
state of a unique client-bean session

.T ci
Because an active client interacts with the bean, this is
often called the conversational state

.
C
Conversational state is retained for the duration of the client-bean

.F a
session, and no longer
When the conversation ends, there is no need to retain the state.

C rm
By default, the bean and its state are retained until timeout.
Complications that come with state:
Deciding what is appropriate conversational state
to fo
Activation and passivation
Ensuring the client always accesses the same bean instance
Cleaning up orphan instances when client ends
ec vo

Copyright IBM Corporation 2008

Figure 3-15. Stateful session beans WD352 / VD3521.0

Notes:
oy si

The state of stateful session beans is not persisted to a database in a way that makes it
available or retrievable by applications.
u

The container manages memory and must sometimes release memory by removing
cl

session beans. It can simply destroy instances of stateless session beans with no impact
on the client. However, it must move stateful session bean instances out of memory and
into backing store, typically a database, so it can retrieve them when needed. This process
Ex

is called "passivation and activation" and should be transparent to the client code.
Maintaining session bean state adds to the workload put on the container and can reduce
application performance.
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-19


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Life cycle of stateless session beans


Stateless beans have two life cycle events:
Creation
Client requests bean Does not

.I. n
Ready
Destruction exist

.T ci
Client no longer needs bean

Life cycle methods and callback methods

.
When you want the opportunity to take action immediately after the

C
.F a
bean is constructed, provide a method annotated @PostConstruct
When you want to take action before the bean is destroyed, provide a

C rm
method annotated @PreDestroy

@PostConstruct
to fo
void initialize( ) {
Date now = Calendar.getInstance().getTime();
}
ec vo

Copyright IBM Corporation 2008

Figure 3-16. Life cycle of stateless session beans WD352 / VD3521.0

Notes:
oy si

The container may keep a number of instances of session beans in a pool rather than
constructing and destructing new instances for every client call. As there is no state, no
u

harm is done by allocating an instance first to one client and later to another.
cl

Callback methods are called by the container, not the client.


Ex
pr

3-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Life cycle of stateful session beans


Stateful beans have three states
and four possible events:
Creation creation
Does not

.I. n
Client requests bean Ready
exist
destruction
Passivation

.T ci
activation
Container stores bean passivation
Activation

.
Container retrieves bean Passivated

C
Destruction

.F a
Client no longer needs bean

C rm
Life cycle methods and callback @PrePassivate
methods: @PreDestroy
@PostConstruct void cleanup() {
to fo
@PostActivate // release resources
@PrePassivate }
@PreDestroy
ec vo

Copyright IBM Corporation 2008

Figure 3-17. Life cycle of stateful session beans WD352 / VD3521.0

Notes:
oy si

The container creates a new instance of a stateful session bean when a client requests it,
and maintains the association between each instance and a specific client throughout the
u

life cycle of the instance. The container can passivate instances at any time and does so to
cl

conserve memory. The container must activate a passivated instance when the client
needs it.
Callback methods are called by the container, not the client.
Ex

A stateful session bean must be serializable because it may be passivated. Passivation


involves serializing the bean and writing it to a persistent store such as a database.
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-21


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Web clients and stateful session beans


The container manages association of client to bean instance,
provided it can tell them apart. What if the client is a servlet
used by different Web application clients?

.I. n
The solution:

.T ci
Declare the bean reference with @EJB at class scope or using an
EJB deployment descriptor
@EJB

.
(name="CounterBean", beanInterface=Counter.class)

C
.F a
public class MyServlet
Access the EJB using JNDI and the declared bean name

C rm
Context ctx = new InitialContext();
Counter counter = (Counter)
ctx.lookup("java:comp/env/CounterBean");
counter.increment();
to fo
Store the interface in the HttpSession object to retrieve as needed
session.setAttribute("counter", counter);
ec vo

Copyright IBM Corporation 2008

Figure 3-18. Web clients and stateful session beans WD352 / VD3521.0

Notes:
oy si

In the example shown in the figure, the @EJB annotation is at the class scope: the
annotation appears above of the class declaration. Placing the annotation at the class level
u

does not inject the EJB interface into the class. Instead it establishes and EJB reference
cl

that can be used with JNDI lookup. This @EJB annotation in the example above is has the
same effect as adding an <ejb-ref> or <ejb-local-ref> element to the web.xml deployment
descriptor.
Ex

When you use the @EJB notation to establish an EJB reference, you must specify both the
bean class name for JNDI lookup and the interface. Then look up the name in the JNDI
context java:comp/env.
pr

This use of the @EJB annotation at class level is common in helper classes for servlets or
in Web applications built upon a framework such as struts or JavaServer Faces.
Another use of the @EJB or @Resource annotations at class level is to enable the class to
dynamically determine what resource or EJB to use at run time rather than at compile time.
That is, the argument of the lookup method may be determined by logic at runtime rather
than by annotations that are resolved at compile and load.

3-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Removing stateful session beans


After the client ends, orphan stateful session beans may reside
in the servers memory space until a timeout condition occurs

.I. n
The solution:

.T ci
Include one method in the business interface that is annotated
@Remove in the bean class

.
Make the client call the annotated method when it is finished with the

C
session bean

.F a
After the client calls the method, the container destroys the bean
instance

C rm
@Remove
public int closedown() {
System.out.println("The final count is "
to fo
+ count);
return count;
}
ec vo

Copyright IBM Corporation 2008

Figure 3-19. Removing stateful session beans WD352 / VD3521.0

Notes:
oy si

A good place to call the closedown method in a Web application is in the callback method
sessionDestroyed of the HttpSessionListener interface.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-23


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Exception handling in session beans


EJBs may throw two kinds of exceptions.

.I. n
Application exceptions are:
All checked exceptions except java.rmi.RemoteExeption

.T ci
Used for situations related to application logic
Examples: insufficient funds, no such item, credit limit exceeded
If not handled, passed by the container back to the client

.
C
System exceptions are:

.F a
All unchecked exceptions plus java.rmi.RemoteException

C rm
What happens in situations that application code cannot anticipate?
Examples: null pointer, array index out of bound, class cast exception
Wrapped by the container in javax.ejb.EJBException objects that
are passed back to the client
to fo
Clients should be coded to handle java.ejb.EJBException and
appropriate application exceptions
ec vo

Copyright IBM Corporation 2008

Figure 3-20. Exception handling in session beans WD352 / VD3521.0

Notes:
oy si

Checked exceptions are the ones you must list in the throws clause of a method.
u

Sometimes, unchecked exceptions can be caught and handled by the EJB.


A client receives the javax.ejb.EJBException or the java.rmi.RemoteException as an
cl

indication of a failure to invoke an enterprise bean method or to properly complete its


invocation. The exception can be thrown by the container or by the communication
Ex

subsystem
between the client and the container.
pr

3-24 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Comparing stateful and stateless session beans


Stateless Stateful

Has conversational state no yes

.I. n
Container can pool instances yes not when active

.T ci
Performance issues unlikely possible
Life cycle events PostConstruct PostConstruct
PreDestroy PrePassivate

.
PostActivate

C
.F a
PreDestroy
Session synchronization for no yes

C rm
transactions

Can be exposed as a Web service yes no


to fo
Can use timers yes no
Extended persistence context no yes
ec vo

Copyright IBM Corporation 2008

Figure 3-21. Comparing stateful and stateless session beans WD352 / VD3521.0

Notes:
oy si

A later lecture discusses timers in detail.


u

The persistence context relates to entity beans and enables the use of entity beans by
EJBs. This course discusses entity beans in the units on JPA. All activities that EJBs
cl

perform on persistence data, including starting and stopping transactions, occur within a
context managed by the EJB container. EJBs access entities through an entity manager
that is associated with the entity context. Using entity beans in stateful session beans has
Ex

implications because the container can ensure that the persistence context is available
when a stateful session bean that has been passivated is activated.
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-25


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Typical session bean development process


Building a Java EE application In Rational Application Developer:
1. Set up projects:
Create an EAR project

.I. n
Create EJB project as a module of the EAR
2. Create the EJB:

.T ci
Create the bean class
Promote business methods to the local or remote interface
3. To unit test:
Publish the EAR project to the test server

.
Use the servers Universal Test Client test to EJB methods

C
4. Add other modules to the EAR:

.F a
Web application as a Dynamic Web project
Java client application as Application client project

C rm
Utility jars as Java projects
JPA projects to hold JPA entity beans
5. To integration test:
Configure resources on the server as required
Publish the EAR project to the test server
Run the application.
to fo
6. To deploy:
Export the EAR project to an EAR file on the file system
Install the EAR file on a staging or production server
ec vo

Copyright IBM Corporation 2008

Figure 3-22. Typical session bean development process WD352 / VD3521.0

Notes:
oy si

You can build the various projects in any order. For example you can start by creating an
EAR project and then create other projects as modules within the EAR, or you can build the
u

other modules independent projects and later add them as modules to a new or existing
cl

EAR project.
Rational Application Developer has a create-EJB wizard that lets you write the bean class
and then promote methods to the interface. You can also use the create-Java-interface and
Ex

create-Java-class wizards and manually add annotations to make an EJB.


As well as using the Universal Test client, you can unit-test EJBs using testing tools such
as JUnit 4 to test the bean class in an SE environment. Testing with JUnit can be quick and
pr

convenient. However JUnit 4 is limited to testing single EJBs that do not call other EJBs or
require resources (such as data sources) that are managed the server.
References to data sources, messaging resources (JMS queues, topics, connection
factories), and other resources can be injected into EJB beans using annotations. In
addition you must configure these resources on the server and specify bindings (map
resource references to configured resources) in the WebSphere Bindings deployment

3-26 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty descriptor, file ibm-ejb-jar-bnd.xml. For details, refer to the section Application Bindings in
the WebSphere Application Server v7.0 Information Center.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-27


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Checkpoint
1. If you are writing an application for online shopping in which
a customer adds items to a shopping cart and then proceeds
to checkout, where would you store the shopping cart?

.I. n
2. Why are stateless session beans potentially more scalable

.T ci
than stateful?

.
3. What types of interfaces are allowed for all session beans?

C
.F a
4. How does the container know whether a particular session
bean should be stateless or stateful?

C rm
5. Give an example of a client that cannot use dependency
injection to access a session bean
to fo
ec vo

Copyright IBM Corporation 2008

Figure 3-23. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.

4.
pr

5.

3-28 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Unit summary
Having
Havingcompleted
completedthis thisunit,
unit, you
youshould
shouldbe beable
ableto:
to:
Define
Definesession
sessionbeans
beans

.I. n
List
Listreasons
reasonsfor forusing
usingsession
sessionbeans
beans
Create
Createsession
sessionbean
beanclasses
classesandandinterfaces
interfaces

.T ci
Access
Accesssession
sessionbeans
beansfrom
fromclient
clientcode
code
Use
Use the session context to interactwith
the session context to interact withcontainer-managed
container-managed

.
resources
resources

C
.F a
Use
Useannotations
annotationswithwithsession
sessionbeans
beans
Describe
Describeapplication
applicationbindings
bindingsfor forsession
sessionbeans
beans

C rm
Explain
Explainthethelife
lifecycle
cycleof
ofsession
sessionbeans
beansand anduse
uselife
lifecycle
cyclecall
call
back methods
back methods
Compare
Comparestateful
statefuland
andstateless
statelesssession
sessionbeans
beans
to fo
ec vo

Copyright IBM Corporation 2008

Figure 3-24. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 3. Session EJBs 3-29


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

3-30 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 4. The library case study

What this unit is about


This unit introduces the application and case study upon which all
hands-on exercises except the first are based.

.I. n
What you should be able to do

.T ci
After completing this unit, you should be able to:

.
Describe the use cases in the case study

C
.F a
Describe the architecture of the library application
List the main components in the loan subsystem of the library

C rm
application and state how they relate to each other
Explain how each upcoming exercise contributes to the
development of a working application
to fo
How you will check your progress
Exercise
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives

After
Aftercompleting
completingthis
thisunit,
unit,you
youshould
shouldbe beable
ableto:
to:
Describe
Describethetheuse
usecases
casesininthe
thecase
case study
study

.I. n
Describe
Describe the architecture of the libraryapplication
the architecture of the library application
List
Listthe
themain
main components
components in in the
theloan
loansubsystem
subsystemof ofthe
thelibrary
library

.T ci
application
applicationand
andstate
statehow
howthey
theyrelate
relatetotoeach
eachother
other
Explain
Explain how
how each
each upcoming
upcoming exercise
exercise contributes
contributes to
to the
the

.
development
developmentof ofaaworking
workingapplication
application

C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 4-1. Unit objectives WD352 / VD3521.0

Notes:
oy si

This unit introduces the application and case study upon which all hands-on exercises
except the first are based.
u
cl
Ex
pr

4-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The library system and its subsystems


The case study models a library
that maintains a catalog of books

.I. n
The library has two kinds of

.T ci
users:
Patrons
Librarians

.
C
A complete library system has

.F a
at least three subsystems:

C rm
Catalog subsystem
A book is a catalog entry
A copy of a book may be loanable
Patron subsystem
to fo
Maintains user profiles
Loan subsystem
Records loans
Supports borrow and return
ec vo

Copyright IBM Corporation 2008

Figure 4-2. The library system and its subsystems WD352 / VD3521.0

Notes:
oy si

A book has a title, unique ISBN, and other information. For each book in the library catalog,
the library keeps a number of physical copies. When a patron borrows a book, the item
u

loaned is actually a copy of a book.


cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The database used by the library application

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 4-3. The database used by the library application WD352 / VD3521.0

Notes:
oy si

The slide shows an entity relationship diagram of the seven tables in the library database.
The diagram was generated in Rational Application Developer.
u

Note the symbols for:


cl

Table (looks like a table)


Primary key (yellow key)
Ex

Foreign key (blue key)


Column (looks like a column in the table)
pr

4-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Use cases in the loan subsystem


Patrons use a Web application to access the library and
perform any of the following actions

.I. n
.T ci
Borrow copy
extends

.
Return copy Browse catalog

C
.F a
extends
Reserve item

C rm Cancel reserved item


to fo
Borrow copies of
reserved item
ec vo

Copyright IBM Corporation 2008

Figure 4-4. Use cases in the loan subsystem WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Phase 1: Provide basic business operations


Exercises 3 and 4 start by creating session beans that
provide business functions that let patrons:
Borrow one copy of a book at a time

.I. n
Reserve a set of books to borrow together

.T ci
Exercise 5 tests with a Java client application

.
Item

C
reserver

.F a
Java

C rm
JDBC
classes API DB

Borrower
to fo
Java
client
application
ec vo

Copyright IBM Corporation 2008

Figure 4-5. Phase 1: Provide basic business operations WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

4-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Phase 2: Add entity beans for persistence


Exercise 6 creates entity beans
and maps them to a database JPA Entity beans

.I. n
Object associations:

.T ci
Abstract
A book may have many authors Book
An author may have many books

.
A book has one abstract Author

C
A book may have several copies

.F a
A copy may have one loan Copy
record

C rm
A loan record is for to one patron
One patron may have several
loan records (copies on loan) Onloan
DB
to fo
Patron
ec vo

Copyright IBM Corporation 2008

Figure 4-6. Phase 2: Add entity beans for persistence WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Phase 3: Add interfaces to the entity beans


Exercise 7 creates session beans that are faades for the
entity beans

.I. n
Book
Catalog

.T ci
Manager
Author

.
Abstract DB

C
.F a
LoanManager
Copy

C rm Onloan
to fo
PatronManager Patron

Business logic and entity facade Persistence


ec vo

Copyright IBM Corporation 2008

Figure 4-7. Phase 3: Add interfaces to the entity beans WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

4-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Phase 4: Complete borrow-return functionality


Exercise 8 adds a message-driven bean and session bean to
complete the business operation of returning a copy

.I. n
Returner

.T ci
When a copy is returned, it waits in

.
a queue for processing

C
.F a
C rm
CopyReceiver LoanManager Loan DB
to fo
MDB
ec vo

Copyright IBM Corporation 2008

Figure 4-8. Phase 4: Complete borrow-return functionality WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Phase 5: Add the user interface


Exercise 9 imports a Web application and integrates it with
the EJBs

.I. n
.T ci
Item Catalog
Reserver Manager

.
Web

C
app

.F a
Borrower LoanManager

C rm Returner
Patron
Manager
to fo
ec vo

Copyright IBM Corporation 2008

Figure 4-9. Phase 5: Add the user interface WD352 / VD3521.0

Notes:
oy si

The diagram above does not show that the Web application also uses the CatalogManager
to browse the library and PatronManager to authenticate patrons at login.
u
cl
Ex
pr

4-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Phase 6 and 7: Complete the loan subsystem

Phase 6 adds quality of service

.I. n
Exercise 10 explores transactional integrity

.T ci
Exercise 11 adds a timer to demonstrate additional EJB features

.
C
Exercise 13 adds security

.F a
Phase 7 packages for deployment

C rm
Exercise 14 deploys the application to WebSphere Application
Server
to fo
ec vo

Copyright IBM Corporation 2008

Figure 4-10. Phase 6 and 7: Complete the loan subsystem WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The final application architecture


Clients Session beans MDB Persistence
Entity beans

.I. n
Book
Item Catalog

.T ci
Reserver Manager
Author
Web
app

.
Abstract

C
Borrower DB

.F a
LoanManager Copy

C rm
Loan
Copy
Copy
Receiver
Returner Receiver
Patron
to fo
PatronManager
ec vo

Copyright IBM Corporation 2008

Figure 4-11. The final application architecture WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

4-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Unit summary
Having
Havingcompleted
completedthis
thisunit,
unit, you
youshould
shouldbebeable
ableto:
to:
Describe
Describethetheuse
usecases
casesininthe
thecase
case study
study

.I. n
Describe
Describethethearchitecture
architectureofofthe
thelibrary
libraryapplication
application
List
Listthe
themain
main components
components in in the
theloan
loansubsystem
subsystemof ofthe
thelibrary
library

.T ci
application
applicationand
andstate
statehow
howthey
theyrelate
relateto
toeach
eachother
other
Explain
Explain how each upcoming exercise contributes to
how each upcoming exercise contributes to the
the

.
development
developmentof ofaaworking
workingapplication
application

C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 4-12. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 4. The library case study 4-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

4-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 5. Strategies for testing EJBs

What this unit is about


This unit explores options for testing EJBs.

.I. n
What you should be able to do

.T ci
After completing this unit, you should be able to:
Distinguish between unit, integration, and other levels of testing

.
List some strategies for unit testing

C
.F a
Use JUnit 4 to unit test EJBs
Describe alternative techniques for testing

C rm
How you will check your progress
to fo
Checkpoint
Exercise
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After completing this unit, you should be able to:
Distinguish between unit, integration, and other levels of

.I. n
testing
List some strategies for unit testing

.T ci
Use JUnit 4 to unit test EJBs
Describe alternative techniques for testing

.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 5-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

5-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Levels and types of testing


Unit testing:
A unit test is a collection of operations designed to verify the
behavior of a single unit within your program

.I. n
In Java, the single unit is almost always a class
A unit testing framework provides classes and tools that make it
easy to write test cases and build up test suites

.T ci
Integration testing:
Verifies the behavior of more than one unit
May have several levels: from two classes to several subsystems

.
Should assume units work and focus on interaction between them

C
Stress testing:

.F a
Measures how performance is affected as the application scales up
to accommodate many users

C rm
Is important for Web applications with expected high volume or
usage peaks
Quality assurance:
Evaluates code against company or other standards
to fo
Acceptance testing:
Provides user feedback on whether the application does what is
required and is easy to use
Testing can involve all of the above and much more
ec vo

Copyright IBM Corporation 2008

Figure 5-2. Levels and types of testing WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Testing EJBs
One of the advantages of EJB 3 over earlier EJB specifications is
simplicity of testing. Java SE ignores EJB annotations so:
You can use unit test frameworks designed for plain old Java objects (POJO)

.I. n
You can add main() method to test and debug like any Java class
Make full use of the debug perspective without the overhead of the server

.T ci
WebSphere Application Server provides the Universal Test Client
Launch the UTC from Rational Application Developer

.
Use JNDI Explorer to look up EJB 3 beans in the UTC

C
.F a
Invoke method on the EJBs and inspect returned values or objects
Test methods that call other EJBs and use resources managed by the server

C rm
Considerations when using test frameworks designed for POJOs on
EJBs:
Unit tests do not allow one EJB to call another
to fo
You are not testing in the EJB container and cannot test with container services
Resources managed by the server are not available
You may have to mock up the persistence environment when entity beans are
involved
ec vo

Copyright IBM Corporation 2008

Figure 5-3. Testing EJBs WD352 / VD3521.0

Notes:
oy si

The UTC is itself a Java enterprise application that runs on the server. Its user interface is a
Web application that runs in a Web browser. It lets you locate EJBs in the JNDI namespace
u

and call methods on them.


cl

Testing an EJB with a unit test such as JUnit tool is worthwhile to ensure that logic within
the bean is implemented correctly in a Java SE environment.
Ex
pr

5-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Testing EJBs using the UTC

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 5-4. Testing EJBs using the UTC WD352 / VD3521.0

Notes:
oy si

In this example, the JNDI Explorer of the UTC was used to look up the local interface for
the ClockBean. Then the getClockInfo(String) method was invoked using the value
u

MEDIUM for the String parameter.


cl

The resulting date and time are displayed in the lower part of the figure.
Ex
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Using a unit-test framework


What to look for in a framework:
Tests are fully automatic and self checking
Test code is separated from production code

.I. n
Tests simply indicate that they passed or failed no need to

.T ci
compare output with known or expected results
The framework handles user interface and error reporting
Creating and adding new tests is easy

.
C
.F a
Strategies in designing tests:
Write test cases before the code is written

C rm
Write test cases to handle both valid and improper input values
Test all public methods (except getters and setters)
If you find a bug not caught by your test suite, add a test case to
catch it
to fo
Build up a test suite by adding tests to run for regression testing
Do not overdo it: unnecessary tests can slow you down
ec vo

Copyright IBM Corporation 2008

Figure 5-5. Using a unit-test framework WD352 / VD3521.0

Notes:
oy si

Some recommended practices for writing test code:


u

Make sure the test code is no longer than the code under test.
Mirror the package structure of your production classes in your test classes.
cl

Give the test class the same name as the class under test plus the suffix "Test".
Ex
pr

5-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

What is JUnit?
An open source, unit testing framework for Java
http://junit.org

.I. n
Provided by Rational Application Developer as a plug-in
Includes an automated test runner

.T ci
JUnit view reports test success or failure

Write tests and test suites as simple Java classes

.
JUnit 4 uses annotations to simplify coding

C
.F a
Assert methods in the test code reduce success or failure to clear-cut
criteria

C rm
The alternatives to use when more than one EJB is involved:
Universal Test Client of WebSphere Application Server
A simple servlet in a Web application can run in the same JVM and
to fo
use the local interface
A Java client application runs in the client container and uses the
remote interface
ec vo

Copyright IBM Corporation 2008

Figure 5-6. What is JUnit? WD352 / VD3521.0

Notes:
oy si

Writing an EJB client application or Web application is more work than creating JUnit tests,
and does not lend itself to building test suites. But it does test the EJB in the container.
u

This course uses JUnit 4 because it is included in Rational Application Developer. A


cl

number of open-source tools that are better suited to testing EJB 3 beans and are now
available as open-source products. For information on JUnitEE from SourceForge.net, see
http://www.junitee.org.
Ex
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Anatomy of a JUnit 4 test case


public class MyClassTest {
@Test
Public void testCondition() {

.I. n
// code that uses the methods being tested
assertTrue(<condition> ); // or other assert

.T ci
}
@Test (expected=ExpectedException.class) {
public void testException() {

.
// code that should throw an ExpectedException

C
.F a
}
@Before

C rm
public void setup() {
//code that prepares for the test
}
@After
to fo
Public void after() {
// code that cleans up after the test
}
}
ec vo

Copyright IBM Corporation 2008

Figure 5-7. Anatomy of a JUnit 4 test case WD352 / VD3521.0

Notes:
oy si

The @Before and @After setup and closedown methods are optional.
u

Unit has more annotations and option attributes than are shown above. It also provides
several overloaded assert methods, including:
cl

assertTrue(condition)
assertEquals(object0, object1)
Ex

assertNull(object) and assertNotNull(object)


assertSame(object0, object1) and assertNotSame(object0, object1)
An excellent guide to JUnit 4, JUnit Cookbook by Kent Beck and Erich Gamma, is available
pr

online at http://junit.sourceforge.net/doc/cookbook/cookbook.htm

5-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Anatomy of a test suite


package app.packages.tests;
import org.junit.runner.RunWith;

.I. n
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

.T ci
@RunWith(Suite.class)

.
@SuiteClasses( { MyClassTestA.class,

C
.F a
MyClassTestB.class,
MyClassTestC.class } )

C rm
public class MyClassTests {
// no code required here
to fo
}
ec vo

Copyright IBM Corporation 2008

Figure 5-8. Anatomy of a test suite WD352 / VD3521.0

Notes:
oy si

The code above runs three test cases, one after the other, and reports success if all tests
are successful.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JUnit tools in Rational Application Developer


Rational Application Developer has a JUnit wizard.
Simplifies generating test cases and test suites
Can add JUnit jar to project build path

.I. n
Running the test is as simple as Run Run As JUnit Test

.T ci
Tests run as ordinary Java classes. No server is required
Results appear in the JUnit view

.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 5-9. JUnit tools in Rational Application Developer WD352 / VD3521.0

Notes:
oy si

You run a number of JUnit tests in the exercises. The image above is from one of them.
u
cl
Ex
pr

5-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint

1. When unit testing an EJB with JUnit, does the EJB run in a
Java EE container?

.I. n
2. Name some alternatives to using JUnit for unit testing

.T ci
3. What are some limitations of testing with JUnit?

.
C
.F a
4. After extensive testing with JUnit, is EJB testing complete?

C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 5-10. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.
pr

Copyright IBM Corp. 2008 Unit 5. Strategies for testing EJBs 5-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit summary
Having completed this unit, you should be able to:
Distinguish between unit, integration, and other levels of

.I. n
testing
List some strategies for unit testing

.T ci
Use JUnit 4 to unit test EJBs
Describe alternative techniques for testing

.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 5-11. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

5-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 6. EJB clients

What this unit is about


This unit explains how to write Java classes that are clients of EJBs.

.I. n
What you should be able to do

.T ci
After completing this unit, you should be able to:
State which types of EJB clients can be local and remote

.
Explain the considerations for remote clients relating to remote

C
.F a
method invocation
Use annotations for dependency injection in client code

C rm
State default resolution for EJB annotations
List conditions where the client must use JNDI rather than
dependency injection to access EJBs
to fo
Handle exceptions thrown during EJB execution
Create and run Java client applications
ec vo

How you will check your progress


Checkpoint
oy si

Exercise
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After completing this unit, you should be able to:
State which types of EJB clients can be local and remote

.I. n
Explain the considerations for remote clients relating to remote
method invocation

.T ci
Use annotations for dependency injection in client code
State default resolution for EJB annotations

.
List conditions where the client must use JNDI rather than

C
.F a
dependency injection to access EJBs
Handle exceptions thrown during EJB execution

C rm
Create and run Java client applications
to fo
ec vo

Copyright IBM Corporation 2008

Figure 6-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

6-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Kinds of EJB clients


Web client
Consists of a set of dynamic Web pages based on various markup
A browser which renders the pages (HTML, DHTML, )

.I. n
Sometimes called thin client as heavy

.T ci
operations are pushed to the business tier

Application client

.
May have richer interface than a browser can

C
.F a
give based on Java widgets (Swing, AWT, SWT)
May be command line programs

C rm
May run in Java SE or a Java EE client container
Client container is a managed client environment
Client container is provided by the server provider
May be packaged with the enterprise application
to fo
Web service consumer
Can access an EJB through SOAP messaging
ec vo

Copyright IBM Corporation 2008

Figure 6-2. Kinds of EJB clients WD352 / VD3521.0

Notes:
oy si

Of course EJB can be clients of other EJBs too.


u

Some acronyms and terms:


HTML (HyperText Markup Language) is an XML-like tagging language understood by
cl

Web browsers.
DHTML (Dynamic HTML) consists of HTML mixed with JavaScript to provide client-side
Ex

processing, usually to enrich the user interface.


Swing is a large library of classes provided by Java SE for creating flexible and
professional quality graphical user interfaces.
pr

AWT: Abstract Window Toolkit is the original, simple set of classes provided by Java SE
for creating graphical user interfaces.
SWT: Standard Widget Toolkit is similar to AWT but uses native operating system
libraries widgets.

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Session beans can have local and remote clients


Client type Local Remote
EJBs and POJO in EJB
containers @Local @Remote

.I. n
Classes in Web

.T ci
applications @Local @Remote
Classes in Java client
applications @Remote

.
C
Web service consumers

.F a
@WebService

C rm
Local clients run in the same JVM as the EJB
Arguments are passed by reference
Remote clients run in a different JVM from the EJB
to fo
Arguments are passed by value over Remote Method Invocation (RMI)
Return type and arguments must be serializable
Methods do not have to throw java.rmi.RemoteException unless the
business interface extends java.rmi.Remote
ec vo

Copyright IBM Corporation 2008

Figure 6-3. Session beans can have local and remote clients WD352 / VD3521.0

Notes:
oy si

The Web container and EJB container within a server run in the same JVM. Therefore,
Web applications use the local interface to access EJBs on the same server and the
u

remote interface to access EJBs on a different server.


cl

Web service clients are listed above for completeness, but the discussion in the rest of this
lecture does not apply to them.
Ex

Message-driven beans do not have clients that can call methods on the beans. They have
no local or remote interface.
pr

6-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Remote clients use EJB stub and tie proxies


In EJB 3, the container generates wrapper, tie, and stub classes
required because remote access uses RMI-IIOP
Transparent to clients that run in a EJB 3 enhanced client container

.I. n
Server

.T ci
Client
Remote EJB
interface object
Stub

.
Tie

C
.F a
EJB stubs are not generated automatically for clients that run in :
Bare Java SE environment (client code runs in a Java SE JVM)

C rm
Non-WebSphere Application Server environments
WebSphere Application Server environments prior to version 7 or to version 6.1
with the EJB 3.0 fix pack
To fix, run the createEJBstubs command
to fo
Command line utility provided by WebSphere Application Server
Operate on the EAR that contains the application and client
ec vo

Copyright IBM Corporation 2008

Figure 6-4. Remote clients use EJB stub and tie proxies WD352 / VD3521.0

Notes:
oy si

For more information, see the section create stubs command in the WebSphere Application
Server information center at
u

http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Dependency injection by EJB clients


Classes that are managed by a Web, EJB, or client
container can use dependency injection (DI) to access
EJBs with the @EJB annotation

.I. n
public class EJBClient {

.T ci
@EJB
MyEJBInterface myei;
protected void doWork () {

.
//

C
whatever = myei.myMethod(arg1, arg 2);

.F a
//
}

C rm
}

Instead of client retrieving EJB, the container injects it


to fo
Resource injection for resources works in a similar
manner but uses the @Resource annotation
@Resource SessionContext sc;
ec vo

Copyright IBM Corporation 2008

Figure 6-5. Dependency injection by EJB clients WD352 / VD3521.0

Notes:
oy si

Injection can apply to a field or to a getter method.


u
cl
Ex
pr

6-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

More about the @EJB annotation


Placed at class scope, @EJB does not inject an EJB
Declares a reference for future JNDI lookup
Alternative is to add <ejb-ref> or <ejb-local-ref> stanza to

.I. n
deployment descriptor for module containing client

.T ci
To resolve in source code:
import javax.ejb.EJB;

.
C
Attributes of the @EJB annotations are optional:

.F a
name: The logical name of the EJB reference within the declaring

C rm
component's (java:comp/env) environment (String)
beanInterface: name of the beans interface (Class)
beanName: name of the bean class, defaults to unqualified bean class
name (String)
mappedName: server-specific global JNDI name (String)
to fo
@EJB (name="MyEJBBean", beanInterface=MyEJB.class)
public class MyEJBClient {
ec vo

Copyright IBM Corporation 2008

Figure 6-6. More about the @EJB annotation WD352 / VD3521.0

Notes:
oy si

The @EJB notation occurs at field level. The EJB is not initialized explicitly because the
container provides it.
u

Attributes of the @EJB annotations are:


cl

name: The logical name of the EJB reference within the declaring component's
(java:comp/env) environment (String)
Ex

beanInterface: Name of the bean's interface (Class)


beanName: Name of the bean class; defaults to unqualified bean class name (String)
mappedName: Server-specific global JNDI name (String)
pr

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Default resolution of EJB annotations


Providing bindings for EJB references is optional with EJB 3
Set non-default names in file ibm-ejb-jar-bnd.xml in the EJB module.
When no explicit user-defined bindings are specified:

.I. n
The container searches the EJB module for an EJB that implements

.T ci
the interface type referred to.
If it finds exactly one EJB within the module that implements the
interface, it uses that bean as the target for the EJB reference

.
C
package com.ibm.library.loans;

.F a
import javax.ejb.EJB;
public class AClient { import javax.ejb.Remote;
@Remote

C rm
@EJB
Borrower borrower; public interface Borrower{...

package com.ibm.library.loans;
to fo
import javax.ejb.Stateless;
@Stateless
public class BorrowerImpl implements Borrower {...
ec vo

Copyright IBM Corporation 2008

Figure 6-7. Default resolution of EJB annotations WD352 / VD3521.0

Notes:
oy si

If the EJB container finds no explicit resolution using reference target bindings in the EJB
module's ibm-ejb-jar-bnd.xml file, then the container searches within the referring module
u

for an enterprise bean that implements the interface type you have defined within the
cl

reference.
If it finds exactly one enterprise bean within the module that implements the interface, it
uses that enterprise bean as the target for the EJB reference.
Ex

If the container cannot locate an enterprise bean of that type within the module, it expands
the search scope to the application that the module is part of, and search other modules
within that application that are assigned to the same application server as the referring
pr

module.
References to enterprise beans in a different application, enterprise beans in a module
assigned to a different application server, or to enterprise beans residing in a module that
has been assigned to a WebSphere Application Server cluster, must be explicitly resolved
using reference target bindings in the EJB module's ibm-ejb-jar-bnd.xml file, or the Web
module's ibm-web-bnd.xml file.

6-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

WebSphere default bindings for bean interfaces


Default binding use different sub-contexts of the WebSphere
JNDI namespace.

.I. n
If more than one EJB implements the same interface, either:
Provide explicit binding for each EJB that implements the interface

.T ci
Disable short default bindings for the application
Description Binding pattern

.
C
Short form local ejblocal:<package.qualified.interface>

.F a
interfaces

C rm
Short form remote <package.qualified.interface>
interfaces

Long form local ejblocal:<component-id>#<package.qualified.interface>


interfaces
to fo
Long form remote ejb/component-id># <package.qualified.interface>
interfaces
ec vo

Copyright IBM Corporation 2008

Figure 6-8. Visualization of client interaction with session bean WD352 / VD3521.0

Notes:
oy si

The table shown above also appears in Unit 3, Introduction to EJBs.


u

For more information, see section EJB 3.0 application bindings overview in the WebSphere
Application Server V7.0 Information Center at
cl

http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp
The information center explains how to disable short default name bindings by configuring
Ex

custom properties of the JVM used by WebSphere Application Server.


pr

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Review of JNDI
Classes not managed by an EE container must use JNDI to access a
session EJB
Java application not running in a client container

.I. n
Helper classes, or non-managed classes in the container

To use JNDI, the client must:

.T ci
1. Get the JNDI context
Context ctx = new InitialContext();

.
C
2. Look up the EJB by name

.F a
Use the WebSphere default name (short form shown here):
Local: ctx.lookup (

C rm
"ejblocal:<package.qualified.interface>")

Remote: ctx.lookup("<package.qualified.interface>")

Use the JNDI name specified in an @EJB annotation at class level


to fo
context.lookup ("java:comp/env/<beanName>")
Use the JNDI name specified in the deployment descriptor

3. Cast object to interface type and call methods


ec vo

Copyright IBM Corporation 2008

Figure 6-9. Review of JNDI WD352 / VD3521.0

Notes:
oy si

Instantiate the context and call the lookup method in a try block because either operation
may throw an exception of type javax.naming.NamingException.
u

Recall that servlets and classes called in servlets must take special steps when accessing
cl

stateful session beans to ensure instances of the EJB are not shared by Web clients. The
two key steps are
Ex

Use JNDI to access the EJB.


Store the EJB object returned in the http session and retrieve it from the session when
needed.
pr

6-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Exception handling
Clients should catch exceptions and handle them gracefully

.I. n
The client may receive:
Application exceptions

.T ci
Checked exceptions (excluding javax.rmi.RemoteException)

javax.ejb.EJBException

.
Returned after a system exception (or

C
.F a
javax.rmi.RemoteException)occurs

C rm
EJB clients do not receive javax.rmi.RemoteException
to fo
ec vo

Copyright IBM Corporation 2008

Figure 6-10. Exception handling WD352 / VD3521.0

Notes:
oy si

As EJBs may be remote objects, a RemoteException may be thrown as result calling a


method of the EJB. When that happens, the container returns an EJBException to the
u

client. EJB clients never receive a RemoteException.


cl
Ex
pr

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-11


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Java client applications


Java client applications are ordinary Java applications that use EJBs.

Java clients must access EJBs through their remote interfaces

.I. n
WebSphere Application Server provides a Java EE client container to

.T ci
be installed on remote workstations that run client applications
Provides access to JNDI service of the server
Supports dependency injection in client classes

.
You can install the same EAR on both server side and client side

C
.F a
Gives you launchClient command to start the client

In a pure SE environment, you must:

C rm
Put EJB module jars on class path to resolve references
Add arguments when instantiating JNDI context to locate server
Use JNDI to access all EJBs
Post-process the EAR by running WebSphere createEJBstubs utility
to fo
To develop a Java client in Rational Application Developer:
1. Select to create a client module when creating an EAR project or
2. Create a Java EE client project and add to an existing EAR project
ec vo

Copyright IBM Corporation 2008

Figure 6-11. Java client applications WD352 / VD3521.0

Notes:
oy si

To test within Rational Application Developer, set up a run configuration for the client
project. Then you can use the Run As Run option on the context menu to launch the
u

client.
cl
Ex
pr

6-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint

1. Is a Web application running on the same server as the


EJB container, a local or remote client?

.I. n
.T ci
2. Name a type of client that is always remote

.
3. Do remote EJB clients have to:

C
.F a
a) Handle javax.rmi.RemoteException objects?

C rm
b) Ensure argument objects are of Serializable types?
c) Be enhanced by the createEJBstubs utility before being run?
to fo
4. Does the @EJB annotation appear at class or field level?
ec vo

Copyright IBM Corporation 2008

Figure 6-12. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.

b)
pr

c)

Copyright IBM Corp. 2008 Unit 6. EJB clients 6-13


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit summary
Having completed this unit, you should be able to:
State which types of EJB clients can be local and remote

.I. n
Explain the considerations for remote clients relating to remote
method invocation

.T ci
Use annotations for dependency injection in client code
State default resolution for EJB annotations

.
List conditions where the client must use JNDI rather than

C
.F a
dependency injection to access EJBs
Handle exceptions thrown during EJB execution

C rm
Create and run Java client applications
to fo
ec vo

Copyright IBM Corporation 2008

Figure 6-13. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

6-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 7. Introduction to the Java Persistence API


(JPA)

What this unit is about


This unit gives an introduction to the Java Persistence API. It focuses

.I. n
on the nature and life cycle of entity objects and the role of the entity
manager.

.T ci
What you should be able to do

.
C
After completing this unit, you should be able to:

.F a
List the three areas of Java persistence

C rm
Define JPA entities
Show the relationship between EJB 3 architecture and the
persistence layer
to fo
List the requirements of entity classes
Describe field and property-based access in entities
List the elements of a JPA persistence provider
ec vo

Name the two types of entity managers


Explain how to inject an entity manager into a session bean
List the life cycle states of an entity bean and use the entity
oy si

manager to change state


Use callback methods and life cycle listeners
u
cl

How you will check your progress


Checkpoint
Ex

Exercise following unit 8


pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis thisunit,
unit,you
youshould
shouldbebeable
ableto:
to:
List
Listthe
thethree
threeareas
areasof ofJava
Javapersistence
persistence

.I. n
Define
DefineJPAJPAentities
entities
Show
Show the relationshipbetween
the relationship betweenEJB EJB33architecture
architectureandandthe
the

.T ci
persistence
persistencelayer layer
List
Listthe
therequirements
requirementsof ofentity
entity classes
classes

.
Describe
Describefieldfieldand
andproperty-based
property-basedaccess accessin inentities
entities

C
.F a
List
Listthe
theelements
elementsof ofaaJPA
JPA persistence
persistence provider
provider
Name the two types of entity
Name the two types of entity managers managers

C rm
Explain
Explainhowhowto toinject
injectan
anentity
entity manager
managerinto intoaasession
sessionbean
bean
List
Listthe
thelife
lifecycle
cyclestates
states ofof an
an entity
entitybean
beanand anduse
usethe
theentity
entity
manager
managerto tochange
changestate
state
to fo
Use
Usecallback
callbackmethods
methodsand andlife
lifecycle
cyclelisteners
listeners
ec vo

Copyright IBM Corporation 2008

Figure 7-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

7-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java support for persistence


Most enterprise applications use persistent (long living) data
Persistence is typically provided by relational database management systems (RDBMS)

.I. n
Java has included database access since the beginning
Since Java 1.1, support for relational databases is in package java.sql

.T ci
J2EE V1.2 added package javax.sql
Data sources configured in the application server
Connection pooling managed by application server

.
Distributed transactions global transactions involving multiple resources

C
J2SE V1.4 combined java.sql and javax.sql in JDBC 3

.F a
C rm
Java Persistence API (JPA) combines the best features from previous
persistence mechanisms such as:
Java Database Connectivity (JDBC) APIs
Object Relational Mapping (ORM) frameworks
to fo
Java Data Objects (JDO)

JPA supports the features provided by JDBC without requiring the


knowledge of the specific programming models defined by the various JDBC
implementations
ec vo

Copyright IBM Corporation 2008

Figure 7-2. Java support for persistence WD352 / VD3521.0

Notes:
oy si

Other forms of persistence supported by Java include serialization. For example, you can
encode classes and write them to files.
u

The javax.sql portion of JDBC and JNDI are two of several Java features originally
cl

introduced in Java Enterprise Edition but later shifted to Standard Edition. As a result, some
features of Java SE require the presence of an application server.
Ex

JPA combines the best features from previous persistence mechanisms such as Java
Database Connectivity (JDBC) APIs, Object Relational Mapping (ORM) frameworks, and
Java Data Objects (JDO).
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Three areas of Java persistence


Java persistence consists of three areas:

.I. n
The Java persistence API
An implementation that supports JPA entities

.T ci
Object-relational mapping (ORM)
Specified by JPA metadata

.
C
Java Persistence Query language (JPQL)

.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 7-3. Three areas of Java persistence WD352 / VD3521.0

Notes:
oy si

This unit deals with the concepts and architecture of JPA. ORM and JPQL are covered in
following lecture units.
u
cl
Ex
pr

7-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Introducing Java Persistence API


Like all Java standards, Java Persistence API (JPA) started as
a Java Specification Request (JSR) developed through the
Java Community Process (JCP)

.I. n
JSR-220 adopted as Enterprise JavaBeans 3.0 in Java EE 5
JSR-317 in review as of Dec 2008 defines JPA 2

.T ci
Original request was for a simplification of entity beans

.
Evolved into POJO persistence technology

C
No mandatory interfaces to implement

.F a
Annotations to simplify coding

C rm
Scope expanded at request of community
to support general use in Java EE
and Java SE environments
to fo
JPA for WebSphere Application Server is built on the Apache
OpenJPA open source project
OpenJPA @ http://openjpa.apache.org
ec vo

Copyright IBM Corporation 2008

Figure 7-4. Introducing Java Persistence API WD352 / VD3521.0

Notes:
oy si

The JPA implementation for WebSphere Application Server is built on the Apache
OpenJPA open source project.
u

Using OpenJPA as a base implementation, WebSphere Application Server employs


cl

extensions to provide additional features and utilities for WebSphere Application Server
customers.
Ex

All OpenJPA functionality, extensions, and configurations are unaffected by the


WebSphere Application Server extensions.
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Entity objects provide persistence


In Java EE 5, entity objects are not EJBs; they are POJOs
You can use entity objects (JPA entities) in Java SE or Java EE

.I. n
JPA entities are ordinary JavaBeans. They:
Are not remotely accessible

.T ci
Have a persistent identity distinct from their object reference

JPA defines a set of annotations for:

.
Object-relational mapping

C
.F a
SQL-like queries
Objects that manage persistence

C rm
JPA includes XML files:
persistence.xml: defines the database connection properties or data source
orm.xml: Optional object-relational mapping, alternative to annotations
to fo
Package xml files like a deployment descriptor, in the JAR with the entity beans
ec vo

Copyright IBM Corporation 2008

Figure 7-5. Entity objects provide persistence WD352 / VD3521.0

Notes:
oy si

In the EJB 3.0 specification, entity beans have been replaced by the concept of entities,
which are sometimes called entity objects or JPA entities. This terminology distinguishes
u

between EJB 2.1 entity beans and JPA entities.


cl

A JPA entity is a light-weight persistence domain object.


An entity object is a simple Java class that represents a row in a database table in its
Ex

simplest form. Entities objects can be concrete classes or abstract classes. They maintain
states by using properties or fields.
One of the main innovative concepts introduced by EJB 3.0 is the provisioning of a single
persistence standard for the Java platform that can be used in both the Java EE and Java
pr

SE environments, and that can be used to build the persistence layer of a Java EE
application.

7-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Typical application architecture with JPA

Client
tier Web tier Business
EJB Container
Tier

.I. n
.T ci
JPA entities

Dynamic
Web pages JSPs and

.
servlets

C
.F a
EJBs

C rm
Client
applications Application JPA Entity
Implementation Manager
Server
to fo
Client
system
Database Persistence
ec vo

Copyright IBM Corporation 2008

Figure 7-6. Typical application architecture with JPA WD352 / VD3521.0

Notes:
oy si

The figure shows a variation on the Java EE n-tier architecture that includes JPA.
u

Tier 0 is the client tier, as always. Clients may be Java EE client applications that
connect directly to EJB using RMI/IIOP or thin clients using Web browsers that connect
cl

to the Web tier using HTTP.


Tier 1 is the Web tier through which thin clients access the application. The Web tier
Ex

runs in a Web container.


Tier 2 is the business tier. It consists of EJBs that perform core business functionality
and EJBs that act as facades for the JPA entity beans. The entity beans and the EJBs
reside in the EJB container.
pr

The JPA implementation is provided by the application server.


Tier 3 is the persistence tier provided by a relational database management system.
If a Web application contains both the Web and business tier, that is when classes that
perform business logic belong to the Web application and there are no EJBs, the JPA
entities reside in the Web container. To include JPA entities in the Web tier, you must use

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JPA as you would in a Java SE environment. You lose all the advantages of placing entities
in EJB container.
The EntityManager API can persist, update, retrieve, or remove objects from a database.
The EntityManager API and object-relational mapping metadata handle most of the
database operations without requiring you to write JDBC or SQL code to maintain
persistence.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

7-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Primary features of JPA


JPA is a persistence model based on ordinary Java classes
Entity beans are simple Java classes, not EJBs
Can be used in Java SE

.I. n
Database connection properties specified in persistence.xml
Can be used in either the Web or EJB container of a Java EE

.T ci
application server
Data source specified in persistence.xml

.
Supports enriched domain modelling

C
.F a
Object-relational mapping with inheritance and polymorphism

C rm
Provides an expanded query language
Similar to EJB QL, derived from SQL
Also supports SQL queries as native queries
to fo
Standardizes object-to-relational mapping
Using annotations in code or XML deployment descriptors

Allows for pluggable persistence providers


ec vo

Copyright IBM Corporation 2008

Figure 7-7. Primary features of JPA WD352 / VD3521.0

Notes:
oy si

By replacing entity EJBs with POJO entity beans Java EE 5 greatly simplified the task of
developing enterprise applications. One could argue that the Java Community Process
u

successfully realigned the Java platform with the demands and requirements of the IT
cl

community.
By default, the default JPA persistence provider implementation JPA for WebSphere
Application Server is com.ibm.websphere.persistence.PersistenceProviderImpl.
Ex

WebSphere Application sever also provides an OpenJPA provider and lets you use third
party persistence providers. You can configure any of these providers to be the default for a
server.
pr

The JPA specification explicitly defines the object-relational mapping, rather than relying on
vendor-specific mapping implementations.
JPA standardizes the important task of object-relational mapping by using annotations or
XML to map objects into one or more tables of a database.

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The nature of entities


Entities have persistent state
Persist beyond life of application or server
Typically stored in a relational database Client

.I. n
Identity is obtained from the value of the primary key
Beans have object reference distinct from

.T ci
persistent entity POJO entity
Create with Java keyword new and then
POJO entity

.
manipulate in memory

C
Can subclass entity and non-entity classes

.F a
Can be serialized and used as data transfer objects

C rm
Entities are not remotely accessible Entity
Beans are associated with a persistence unit manager
Entity manager operates on the data source
Loads or finds entities
to fo
Persists entities by inserting them into database
Stores or updates entities
Removes or deletes entities
ec vo

Copyright IBM Corporation 2008

Figure 7-8. The nature of entities WD352 / VD3521.0

Notes:
oy si

The persistent state of an entity is represented through persistent fields or persistent


properties. These properties use object-relational mapping annotations to map the entities
u

and entity relationships to the relational data in the underlying data store.
cl

Data transfer objects is a design pattern created largely to solve the problem of how to pass
the data stored in an entity EJB among the layers of a Java EE application. The answer
was to create a class that implements java.io.Serializable and has fields that mirror the
Ex

fields in the entity EJB and to use this data transfer object as an argument or return value.
This requirement for data access object is reduced. However, access objects, or value
objects, are still helpful, especially when the different representations of the same
pr

information is required. Indeed, implementing an access object design pattern is a


recommended practice to avoid cluttering your code with fine grained calls to the entity
bean.

7-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Example entity class for the simplest situation


Entity name is the same as the underlying table name
Fields or properties correspond directly to columns in a single
table, and have the same names

.I. n
All fields or properties follow the default rules for data types

.T ci
The primary key consists of a single field or property
@Entity

.
public class Employee EMPLOYEE

C
.F a
implements Serializable
EMPID DEPT NAME
{

C rm
@Id
private String empid;
private String dept;
to fo
private String name;
/* get and set Methods */
}
ec vo

Copyright IBM Corporation 2008

Figure 7-9. Example entity class for the simplest situation WD352 / VD3521.0

Notes:
oy si

The annotation @Entity makes the class an entity bean.


u

Entity bean classes must be serializable.


Entity beans must have a field that maps to the primary key of the table. If it is a simple
cl

field, use the @Id annotation to indicate it is the identifier of this entity instance. Note that
the @Id annotation is applied to the field empid. This is called field-based access.
Ex

Only two annotations are required when the criteria listed above are met. The two
annotations, combined with default assumptions, provide all required information.
All annotations in this example and throughout this unit are from package
javax.persistence. Import statements are required.
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Entity class requirements


The class must be annotated with the annotation @Entity

One property or field provides persistent identity:

.I. n
The entity manager maps this field to the primary key

.T ci
May be a instance of a key class

The entity bean must have a public or protected no-argument

.
constructor

C
.F a
The entity manager must be able to instantiate objects

C rm
For the class, none of its methods and none of its fields may
be declared final

Persistent instance variables may not be public, and may only


to fo
be accessed directly by the methods of the entity class
Declare fields private or protected
Declare getter and setter methods public
ec vo

Copyright IBM Corporation 2008

Figure 7-10. Entity class requirements WD352 / VD3521.0

Notes:
oy si

An entity class must follow these requirements:


u

The class must be annotated with the javax.persistence.Entity annotation.


The class must not be declared final, and no methods or persistent instance variables
cl

must be declared final.


The entity class must have a no-argument constructor that is public or protected. The
Ex

entity class can have other constructors as well.


The class must define an attribute that is used to identify in an unambiguous way an
instance of that class (it corresponds to the primary key in the mapped relational table).
pr

Both abstract and concrete classes can be entities.


Persistent instance variables must be declared private, or protected.
If an entity instance be passed by value as a detached object, such as through a
session bean's remote business interface, the class must implement the Serializable
interface.

7-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Field-based and property-based access


You can access the persistent state of an entity through either
instance variables or JavaBean-style properties, but not

.I. n
through both
You cannot mix field-based and property-based access in one entity

.T ci
bean.

.
In field-based access:

C
Annotations are applied to instance variables

.F a
All fields must be private or protected

C rm
In property-based access:
The entity must follow JavaBeans method conventions
to fo
Object-relational annotations are applied to get and set methods
All get and set methods must be public
ec vo

Copyright IBM Corporation 2008

Figure 7-11. Field-based and property-based access WD352 / VD3521.0

Notes:
oy si

Field-based access is used throughout this course.


u

According to JavaBeans method conventions:


For every property type of the entity, except type boolean, there is a get method
cl

getProperty() and set method setProperty(). For example, if the Employee has a field
called name, the class defines getName() and setName().
Ex

For booleans, the get method is called isProperty() instead of getProperty().


Get and set methods are also called getters and setters or accessors and mutators.
The field is private or protected, so that all the client code can see is the getter and
pr

setter.
The get and set methods define a property and are all that is visible to the outside
world. There might not actually be a corresponding property.

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Example of another JPA entity class: Account


@Entity
@Table(name="ACCOUNT", schema="PWIN")
public class AccountData implements Serializable

.I. n
{ private String id;
private String type;

.T ci
@Id
@Column(name="ACCID")

.
public String getId()

C
{ return id; }

.F a
public void setId(String id)

C rm
{ this.id = id; }
@Column(name="TYP", nullable=false)
public String getType()
{ return type; }
to fo
public void setType(String type)
{ this.type = type; }
//
ec vo

Copyright IBM Corporation 2008

Figure 7-12. Example of another JPA entity class: Account WD352 / VD3521.0

Notes:
oy si

Object-relational mapping (ORM) is the topic of the next presentation in this course. This
presentation introduces the @Table, @Id, and @Column annotations only.
u

The JPA makes the following assumptions about the underlying database table:
cl

All columns are nullable.


The length of a string column is 255 or less.
Ex

The precision and scale of a numeric column are both 0.


All columns are insertable and updatable.
If any of these assumptions are false, the @Column annotation must be used to specify
pr

override the default.


In the class above the annotations are applied to get and set methods rather than to fields.
This is called property-based access.

7-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Elements of a JPA persistence provider


Persistence unit
Meta-data that describes the relationship of entity class objects to a
relational database

.I. n
Persistence context

.T ci
The set of active instances that the application is manipulating
currently
EntityManager

.
C
The resource manager that maintains the active collection of entity

.F a
objects that are being used by the application
An application in a container can obtain the EntityManager through

C rm
injection into the application
An instance of an EntityManager represents a persistence context
to fo
ec vo

Copyright IBM Corporation 2008

Figure 7-13. Elements of a JPA persistence provider WD352 / VD3521.0

Notes:
oy si

The entity manager API is used to:


u

Create and remove persistent entity instances


Find entities by their primary key
cl

Query over entities.


Ex

The persistence context:


contains managed entity instances.
The persistence unit:
pr

Determines the set of entities classes that can be managed by an EntityManager


instance.
Is named in persistence.xml. All entity class in a persistence unit must map to the data
source also named in persistence.xml.
Injection of the EntityManager is only supported for the following artifacts:

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

EJB 3.0 session beans


EJB 3.0 message-driven beans
Servlets, Servlet Filters, and Listeners
JSP tag handlers which implement interfaces javax.servlet. jsp.tagext.Tag and
javax.servlet.jsp.tagext.SimpleTag
Java Server Faces (JSF) managed beans

.I. n
The main class of the application client.

.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

7-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The entity manager controls entity life cycles


All mutating operations must occur within a transaction, and update
the database when the transaction commits
EntityManager

.I. n
Transaction required for:
find() contains() persist() merge() remove() refresh() flush()

.T ci
Application space

.
Persistence

C
.F a
Context

C rm
commit
Detached entities:
transient
to fo
new
removed Database
cloned Managed entities
serialized
out of scope
ec vo

Copyright IBM Corporation 2008

Figure 7-14. The entity manager controls entity life cycles WD352 / VD3521.0

Notes:
oy si

The entity manager is the interface to the underlying database. It provides a mechanism to
realize all the create, retrieve, update, and delete operations on the underlying database
u

objects.
cl

Within a persistence context, entities are managed. The entity manager controls their life
cycle, and they can access data store resources.
Ex

When a persistence context ends, previously-managed entities become detached. A


detached entity is no longer under the control of the EntityManager, and no longer has
access to data store resources.
Some methods of the EntityManager interface are:
pr

find(): Loads the entity instance into the persistence context and returns it to the caller if
the primary key is found. Otherwise return null. based on the primary key. The method
signature is find(entityClass, primaryKey).
persist(): Write data to the database (when the transaction commits) - performing a
create or update operation. Add the entity instance to the persistence context.

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

contains(): Check whether the entity instance belongs to the current context.
merge(): Re-attaches detached entities to the current context; merge() is not a void
method. It returns back a managed copy of the argument and its related objects. This
copy can be used for EntityManager operations.
refresh(): Refresh the state of the instance from the database, overwriting changes
made to the entity, if any.

.I. n
remove(): Delete an entity instance from database and persistence context, possibly
with cascading effects if there are relationships between tables.

.T ci
flush(): Synchronize the persistence context to the underlying database. When
database write occurs depends upon flush mode. The default is FlushModeType.AUTO,
where flushing occurs at query execution. Call method

.
setFlushMode(FlushModeType.COMMIT) to flush only when the transaction commits.

C
.F a
An entity is detached after being created with new, until it is attached (becomes managed)
by a call to persist().

C rm
If an entity is returned by calling find(), it is attached.
An entity becomes detached when the entity manager stops managing it. This happens
when it goes out of scope; it is serialized, removed, or cloned,
to fo
Use refresh() and merge() to reattach after an entity has become detached.
ec vo
oy si
u
cl
Ex
pr

7-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The persistence context


A persistence context
represents a set of managed

.I. n
entity instances at run time Entity
Entity

.T ci
Every entity instance must Entity
Entity
have a unique persistence

.
identity in the persistence Persistence context

C
.F a
context

C rm
All entity instances belong to
the same persistence unit EntityManager
and therefore map to the
to fo
same database
Find Lock Query Remove
ec vo

Copyright IBM Corporation 2008

Figure 7-15. The persistence context WD352 / VD3521.0

Notes:
oy si

Locking is an advanced topic related to concurrent use of the database and is covered later
in the next presentation.
u

Locking refers to the approach to potential conflicts when multiple clients may access the
cl

same entity instance. Locks work together with transaction isolation options supported by
the database provider. Taking an optimistic or pessimistic approach is often to a trade-off
between performance and safety. You can call the lock() method on the entity manager,
Ex

specifying LockModeType.READ or LockModeType.WRITE as arguments to ensure the


following do not happen:
Dirty read: Reading uncommitted changes from another transaction
pr

Non-repeatable read: Two or more transactions, independently modifying or deleting a


database row so the state is not consistent over the duration of the transaction

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Managing the life cycle of an entity instance


Entity instances are in one of four
states:
New

.I. n
new
No persistent identity, not associated
with a context

.T ci
Managed persist()
Persistent identity, associated with a clear()
context

.
Promote from new to managed using

C
managed detached
the EntityManager.persist() method

.F a
Detached
Persistent identity, not currently merge()

C rm
remove()
associated with a context
Detach all managed entities using the
EntityManager.clear() method
removed
Removed
to fo
Persistent identity, associated with a
context, scheduled for removal
Move from managed to removed using
the EntityManager.remove() method
ec vo

Copyright IBM Corporation 2008

Figure 7-16. Managing the life cycle of an entity instance WD352 / VD3521.0

Notes:
oy si

A removed entity's data will be actually removed from the data store when the transaction
is completed, or as a result of the flush() operation.
u

Persisting one entity instance may persist other entity instances if they are related through
cl

a relation in which cascade=PERSIST or cascade=ALL was specified. Likewise,


removing one entity instance may remove other entity instances if they are related through
a relation in which cascade=REMOVE or cascade=ALL was specified.
Ex

A discussion of detached entities is coming.


The entity manager method clear removes all entities from the context, causing instances
in memory to be detached. The method merge() merges an entity's state with the current
pr

persistence context.

7-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Life cycle examples (1 of 2)

@PersistenceContext
EntityManager em;

.I. n

.T ci
public Employee createEmployee(empId, dept, name) {
Employee e = new Employee(empId, dept, name);
em.persist(e);

.
return e;

C
}

.F a
C rm
public void removeEmployee(empId) {
try {
Employee e = em.find(Employee.class, empId);
em.remove(e);
to fo
} catch (Exception ex) {
}
}
ec vo

Copyright IBM Corporation 2008

Figure 7-17. Life cycle examples (1 of 2) WD352 / VD3521.0

Notes:
oy si

Some methods of the EntityManager interface are:


u

find(): Return one entity instance. There is no built-in findAll method.


persist(): Write data to the database performing a create or update operation.
cl

contains(): Check whether the entity instance belongs to the current context.
Ex

refresh(): Refresh an entity bean from the database.


remove(): Delete an entity from database, possibly with cascading effects if there are
relationships between tables.
createNamedQuery() and createQuery() create a query object for predefined and
pr

dynamic Java Persistence Query Language (JPQL) statements.


close(): Closes the entity manager.

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Life cycle examples (2 of 2)

@PersistenceContext
EntityManager em;

.I. n

.T ci
public void findDetachAndRemoveEmployee(empId) {
try {
Employee e = em.find(Employee.class, empId);

.
em.clear(); // Employee e is detached

C
.F a
// Return a new managed copy of argument e;
Employee e1 = merge(e);

C rm
em.remove(e1);
} catch (Exception ex) {
}
to fo
}
ec vo

Copyright IBM Corporation 2008

Figure 7-18. Life cycle examples (2 of 2) WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

7-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Handle detached entities with care


Detached entities are useful for accessing entities after
database transactions are complete

.I. n
Detached entities can be a programming headache and can
occur when:

.T ci
An application-managed entity manager is closed or the entity
manager clear() method is called

.
The entity manager is associated with a transaction-scoped

C
persistence context and the transaction commits

.F a
Transaction rollback: detaches all entities in persistent contexts

C rm
associated with the transaction
Stateful session bean that has an extended persistence is
removed: any entities it owns are detached
clear()
The serialized form of an entity is
to fo
always detached managed detached

merge()
ec vo

Copyright IBM Corporation 2008

Figure 7-19. Handle detached entities with care WD352 / VD3521.0

Notes:
oy si

A detached entity is an entity that is no longer managed by the Entity Manager, and there is
no guarantee that the state of the entity is in sync with the database. This is convenient
u

when you want to pass an entity across application tiers. For example, you can detach an
cl

entity and pass it to the Web tier, then update it and send it back to the EJB tier, where the
Entity Manager can merge the detached entity to the persistence context.
In a Web application, a session bean can return detached and even serialized entities to
Ex

the Web tier.


pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Relationships in JPA
The scope of the persistence context is:
A transaction or
The scope of the entity manager in a stateful session bean

.I. n
.T ci
JPA implementation
database

.
1

C
creates

.F a
* Persistence.xml
configures

C rm
EntityManagerFactory Persistence unit
1 1
1 creates
to fo
*
manages
EntityManager Persistence context
* 1
ec vo

Copyright IBM Corporation 2008

Figure 7-20. Relationships in JPA WD352 / VD3521.0

Notes:
oy si

Entity managers may be transaction scoped or have extended scope.


u

Transaction scope:
The persistence context is transaction-scoped. Entity become detached when the
cl

transaction ends.
Extended scope
Ex

Used only with stateful session beans.


The extended entity manager can span transactions and lasts until the session bean is
destroyed.
pr

7-24 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The two types of entity managers


Container-managed (recommended practice):
A typical business operation involves calls across multiple components
that in turn may access the same persistence context

.I. n
The persistence context is propagated by the container
No need for the application to pass references to EntityManager

.T ci
instances from one component to another
@PersistenceContext(name="libraryDB")
EntityManager em;

.
C
Application-managed:

.F a
Application manages the lifetime of the EntityManager

C rm
Application has to keep track of the EntityManager and pass it around
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("libraryDB");
EntityManager em = factory.createEntityManager();
to fo
Both depend on file persistence.xml to specify the
persistence unit
ec vo

Copyright IBM Corporation 2008

Figure 7-21. The two types of entity managers WD352 / VD3521.0

Notes:
oy si

Container-managed means less work on your part but requires the EJB container.
u

Application-managed is more work on your part but is available in the Java SE and on the
Web tier.
cl

The code samples show how the entity manager is obtained in each type.
Ex
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Injecting the entity manager into a session bean

@Stateless
public class AccountManagerBean implements AccountManager {

.I. n
// Container provides the EntityManager
// The persistence unit is AccountDB

.T ci
@PersistenceContext(name="AccountDB")
EntityManager em;

.
// Retrieving a specific account

C
.F a
public AccountDataBean findAccount(int accountId) {
AccountDataBean account = (AccountDataBean)

C rm
em.find(AccountDataBean.class, accountid);
em.find(AccountDataBean.class,
return account;
}
to fo
Many different classes may refer to the same persistence context
Use the entity manager find() method to look up entities by primary key
ec vo

Copyright IBM Corporation 2008

Figure 7-22. Injecting the entity manager into a session bean WD352 / VD3521.0

Notes:
oy si

The association between the persistence context and the persistence unit is established by
a separate file, persistence.xml.
u
cl
Ex
pr

7-26 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Accessing the entity manager from a Java application

public class AccountApplication {


public static void main( String [] args ){

.I. n
// class must instantiate entity manager from factory
EntityManagerFactory factory =

.T ci
Persistence.createEntityManager("AccountDB");
EntityManager em = factory.createEntityManager();

.
// Retrieve a specific account

C
AccountDataBean account = (AccountDataBean)

.F a
em.find(AccountDataBean.class, accountId);
em.find(AccountDataBean.class,

C rm
//
em.close();
return account;
}
to fo
Create the entity manager and then write code to explicitly share it among methods
and classes
You can create and close entity manager instances in many classes
ec vo

Copyright IBM Corporation 2008

Figure 7-23. Accessing the entity manager from a Java application WD352 / VD3521.0

Notes:
oy si

This example shows how you can access the entity manager from the Java SE
environment. It is shown for sake of completeness.
u

An application in a container can obtain the EntityManager through injection into the
cl

application (as shown on the previous slide) or by looking it up in the Java component
namespace.
Ex

If the application manages its persistence, the EntityManager is obtained from the
EntityManagerFactory.
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Persistence units
A persistence unit defines a set of all entity classes that are
managed by entity manager instances in an application

.I. n
This set of entity classes represents the data contained within a single
data store

.T ci
Persistence units are defined by the persistence.xml
configuration file

.
The JAR file or directory whose META-INF directory contains

C
persistence.xml is called the root of the persistence unit

.F a
The scope of the persistence unit is determined by the root of the
persistence unit

C rm
Each persistence unit must be identified with a name that is unique to the
scope of the persistence unit
A persistence unit also specifies:
The data source
to fo
Managed persistence classes
Entity classes, mapped superclasses, and embeddable classes
ec vo

Copyright IBM Corporation 2008

Figure 7-24. Persistence units WD352 / VD3521.0

Notes:
oy si

The application server provides three methods for defining the data sources in the
persistence.xml file.
u

1. Explicitly specify the Java Naming and Directory Interface (JNDI) name in the
cl

persistence.xml file, and the application will directly reference the data source.
2. The application server extends the implementation to allow you to reference data
Ex

sources in component namespace. In the EJB or Web module deployment descriptor


file, this is the <resource-ref> element. You can prefix the data source with
java:comp/env/ so the application indirectly references the data source by using the
local JNDI name.
pr

3. You can declare openjpa.Connection* properties in the persistence unit. An example of


the third method is shown below:
<property name="openjpa.ConnectionDriverName"
value="org.apache.derby.jdbc.EmbeddedDriver" />

7-28 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty <property name="openjpa.ConnectionURL"


value="jdbc:derby:target/database/jpa-test-database;create=true"/>

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Packaging persistence.xml with code


Persistent units can be packaged in:
WAR for use in the Web tier
Place persistence.xml in the WAR files WEB-INF/classes/META-INF

.I. n
directory
EJB JAR file or Java EE utility JAR

.T ci
Place persistence.xml in the EJB JARs META-INF directory
A JAR file that can then be included in a WAR or EAR file

.
Place persistence.xml in the WEB-INF/lib directory of a WAR, in the top

C
level of an EAR file, or in the EAR files library director

.F a
A JAR for a Java SE application

C rm
Place persistence.xml in the JARs META-INF directory

The persistence tools feature of Application Developer


JPA perspective
to fo
Menu option Configure JPA Entities generates the persistence.xml
Tools for object-relational mapping
ec vo

Copyright IBM Corporation 2008

Figure 7-25. Packaging persistence.xml with code WD352 / VD3521.0

Notes:
oy si

If you package the persistence.xml in the Web tier, then you have to do all the same works
as you do in a Java SE environment for managing persistence.
u

It is only when you are running in an EJB container that you can inject the Entity Manager
cl

and have the container manage the transaction.


The recommend practice is to put your JPA entity beans behind a session facade.
Ex
pr

7-30 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

A generic persistence.xml file

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


encoding="UTF-8"?>
<persistence xmlns = >

.I. n
<persistence-
<persistence-unit name="OrgMgr">

.T ci
<description>
This unit manages the employees in the
organization, along with their departments
and projects. It does not rely on any

.
vendor-
vendor-specific features and can thus be

C
.F a
deployed to any persistence provider
</description>

C rm
<jta-
<jta-data-
data-source>jdbc/EmployeeDB</jta-
source>jdbc/EmployeeDB</jta-data-
data-source>
<jar-
<jar-file>EmployeeApp.jar</jar-
file>EmployeeApp.jar</jar-file>
<class>com.ibm.orgmgr.Employee</class>
to fo
<class>com.ibm.orgmgr.Department</class>

</persistence-
</persistence-unit>
</persistence>
ec vo

Copyright IBM Corporation 2008

Figure 7-26. A generic persistence.xml file WD352 / VD3521.0

Notes:
oy si

The exact content of this persistence.xml can depends upon the implementation of JPA
and therefore may vary from server to server.
u

This file defines a persistence unit named OrgMgr that uses a JTA-aware data source
cl

jdbc/EmployeeDB. The jar-file element specifies JAR files that are visible to the
packaged persistence unit that contains managed persistence classes, while the class
elements explicitly name the managed persistence classes.
Ex

The DTD for persistence.xml:


<!ELEMENT persistence (persistence-unit*)>
<!ELEMENT persistence-unit (description?,
pr

provider?,
jta-data-source?,
non-jta-data-source?,
(class|jar-file|mapping-file)*,

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

exclude-unlisted-classes?,
properties?)>
<!ATTLIST persistence-unit name CDATA #REQUIRED>
<!ATTLIST persistence-unit transaction-type (JTA|RESOURCE_LOCAL) "JTA">
<!ELEMENT description (#PCDATA)>

.I. n
<!ELEMENT provider (#PCDATA)>
<!ELEMENT jta-data-source (#PCDATA)>

.T ci
<!ELEMENT non-jta-data-source (#PCDATA)>
<!ELEMENT mapping-file (#PCDATA)>

.
C
<!ELEMENT jar-file (#PCDATA)>

.F a
<!ELEMENT class (#PCDATA)>

C rm
<!ELEMENT exclude-unlisted-classes EMPTY>
<!ELEMENT properties (property*)>
<!ELEMENT property EMPTY>
to fo
<!ATTLIST property name CDATA #REQUIRED>
<!ATTLIST property value CDATA #REQUIRED>
ec vo
oy si
u
cl
Ex
pr

7-32 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

A persistence.xml for WebSphere Application Server

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


encoding="UTF-8"?>
<persistence xmlns = >

.I. n
<persistence-
persistence-unit name="LibraryEntities">
name="

.T ci
<description>
The name of this persistence unit is the same
as the name of the JPA project in Rational

.
Application Developer.

C
There is no need to specify the entity classes

.F a
if the server discovers them by inspecting
the code.

C rm
</description>
<jta-
<jta-data-
data-source>jdbc/libraryDS</jta-
source>jdbc/libraryDS</jta-data-
data-source>
</persistence-
</persistence-unit>
to fo
</persistence>
ec vo

Copyright IBM Corporation 2008

Figure 7-27. A persistence.xml for WebSphere Application Server WD352 / VD3521.0

Notes:
oy si

The listing above is based on the solution to the library enterprise application developed in
exercises in this course. When you are using the default JPA persistence provider (JPA for
u

WebSphere Application Server persistence provider) and using names for entity beans
cl

(bean names that match table name) the minimum you must specify is the name of the
persistence unit and the JNDI name of the data source.
Ex
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JPA entity life cycle callback methods


You can set up callback methods for life cycle events like
persist, load, update, and remove
Typically used to accomplish such tasks as logging, validating data,

.I. n
auditing, sending notifications after a database change, or generating

.T ci
data after an entity has been loaded
The seven callback method annotations are:
@PrePersist @PreRemove @PreUpdate @PostLoad

.
@PostPersist @PostRemove @PostUpdate

C
.F a
Entity life cycle methods can be defined in the entity itself or in

C rm
a separate entity listener class
Using entity listener classes is highly recommended

A callback method is run in the naming, transaction, or security


to fo
context that is active when it is invoked
If in a CMT session bean, the pre-context is often different from the
post-context. For example, before and after a transaction commit
ec vo

Copyright IBM Corporation 2008

Figure 7-28. JPA entity life cycle callback methods WD352 / VD3521.0

Notes:
oy si

Just as in session and message-driven beans, you can do almost anything you need to in
the life cycle callback methods, including invoking an EJB, or using APIs like JDBC or JMS.
u

The callback methods are called under the following conditions:


cl

prePersist(): Before the EntityManager persists an entity instance


postPersist(): After an entity has been persisted
Ex

postLoad(): After an entity has been loaded by a query, find, or refresh operation
preUpdate(): Before a database update occurs to synchronize an entity instance
postUpdate(): After a database update occurs to synchronize an entity instance
pr

preRemove(): Before EntityManager removes an entity


postRemove(): After an entity has been removed
Usage of entity listener classes is highly recommended because defining callback methods
in the entities themselves can clutter the domain model.

7-34 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

JPA entity life cycle listeners


Entity listener classes are POJOs
Implement life cycle callbacks methods with signature

.I. n
void <METHOD>(Object)
The parameter Object specifies the entity instance for which

.T ci
the life cycle event was generated
Register entity listener classes with entities using

.
@EntityListeners annotation

C
.F a
Default listeners can be specified using the deployment
descriptor

C rm
Listeners have a specified execution order
Default listeners are executed first, followed by superclass listeners,
which are then followed by subclass listeners.
to fo
You can exclude default listeners and superclass listeners using:
@ExcludeDefaultListeners
@ExcludeSuperClassListeners
ec vo

Copyright IBM Corporation 2008

Figure 7-29. JPA entity life cycle listeners WD352 / VD3521.0

Notes:
oy si

The execution order for listeners is based on the order in which listeners are specified in
the annotation or deployment descriptor.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Example JPA entity life cycle listener


Implement entity listener class:
public class AccountValidator{

.I. n
public AccountValidator() {
}

.T ci
@PrePersist
public void newAccountValidator(Account account){

.
if (account.getBalance()<MIN_BALANCE ){

C
throw new AccountException(

.F a
" Initial balance for the Account is lower than " +

C rm
" Minimum Balance Allowed"); }
}

Register the listener with the entity


to fo
@EntityListeners(AccountValidator.class)
public class Account implements Serializable {
ec vo

Copyright IBM Corporation 2008

Figure 7-30. Example JPA entity life cycle listener WD352 / VD3521.0

Notes:
oy si

This slide shows an example listener class that can be used to validate an entity state
before an entity is persisted. You can build validation logic in a prePersist() callback, and if
u

the callback fails the entity will not be persisted. For example, when opening any new
cl

account, the amount deposited in the account must be at least the minimum balance
required for the account. The listener validates to ensure that the balance is greater than or
equal to the minimum balance required. If not, an exception is thrown and the entity is not
Ex

persisted.
If the life cycle callback method throws a runtime exception, the intercepted persistence
operation is aborted. This is an extremely important feature to validate persistence
operations. For example, if you have a listener class to validate that all entity data is
pr

present before persisting an entity, you could abort the persistence operation if needed by
throwing a runtime exception.

7-36 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint questions
1. Does the EJB 3 specification cover entity beans?

2. Why must entity beans be serializable?

.I. n
.T ci
3. What annotations are found in all entity beans?

.
4. What file defines the persistence unit?

C
.F a
5. What interface defines the find() method

C rm
to retrieve an entity instance?

6. Name the four phases of the entity


life cycle
to fo
ec vo

Copyright IBM Corporation 2008

Figure 7-31. Checkpoint questions WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.

4.
pr

5.

Copyright IBM Corp. 2008 Unit 7. Introduction to the Java Persistence API (JPA) 7-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit summary
Having
Havingcompleted
completedthis thisunit,
unit, you
youshould
shouldbe beable
ableto:
to:
List
Listthe
thethree
threeareas
areasof ofJava
Javapersistence
persistence

.I. n
Define
DefineJPA JPAentities
entities
Show
Showthe therelationship
relationshipbetween
betweenEJB EJB33architecture
architectureand
andthe
the

.T ci
persistence
persistencelayer layer
List
List the requirementsof
the requirements ofentity
entity classes
classes

.
Describe
Describefieldfieldand
andproperty-based
property-basedaccess accessin inentities
entities

C
.F a
List
Listthe
theelements
elementsof ofaaJPA
JPA persistence
persistence provider
provider
Name
Namethe thetwotwotypes
typesofofentity
entity managers
managers

C rm
Explain
Explainhow howto toinject
injectan
anentity
entity manager
managerinto intoaasession
sessionbean
bean
List the life cycle states of an entity bean and use
List the life cycle states of an entity bean and use the entity the entity
manager
managerto tochange
changestate
state
to fo
Use
Usecallback
callbackmethods
methodsand andlife
lifecycle
cyclelisteners
listeners
ec vo

Copyright IBM Corporation 2008

Figure 7-32. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

7-38 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 8. Object-relational mapping with JPA

What this unit is about


This unit discusses object-relational mapping as supported by JPA.

.I. n
What you should be able to do

.T ci
After completing this unit, you should be able to:
Select the appropriate mapping strategy

.
Use annotations for schema and table mappings

C
.F a
Use annotations for field and relationship mappings, including
primary key classes and embedded classes

C rm
Define one-to-one, one-to-many, many-to-one, and many-to-many
relationships
Describe some of the challenges involved in concurrency of data
to fo
access
Describe techniques used to manage concurrency in JPA
ec vo

How you will check your progress


Checkpoint
Exercise
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthis
thisunit,
unit,you
youshould
shouldbebeable
ableto:
to:
Select
Selectthe
theappropriate
appropriatemapping
mapping strategy
strategy

.I. n
Use
Useannotations
annotationsfor forschema
schemaandandtable
tablemappings
mappings
Use
Use annotations for field and relationship mappings,
annotations for field and relationship mappings, including
including

.T ci
primary
primary key
keyclasses
classesand andembedded
embeddedclasses
classes
Define
Defineone-to-one,
one-to-one,one-to-many,
one-to-many,many-to-one,
many-to-one,and andmany-to-
many-to-

.
many
manyrelationships
relationships

C
.F a
Describe
Describesome
someof ofthe
thechallenges
challengesinvolved
involvedininconcurrency
concurrencyofof
data access
data access

C rm
Describe
Describetechniques
to fo techniquesused usedtotomanage
manageconcurrency
concurrencyininJPA
JPA
ec vo

Copyright IBM Corporation 2008

Figure 8-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

8-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Object-relational mapping strategies


Top-down
Starts with requirements of application

.I. n
Bottom-up
Starts with database tables

.T ci
Meet-in-the-middle
In reality, most mappings are based on realities of database and

.
nature of Java objects

C
.F a
C rm
Object-oriented associations Primary keys
Java types SQL types
Inheritance Foreign keys
to fo
JPA has annotations for most mappings
ec vo

Copyright IBM Corporation 2008

Figure 8-2. Object-relational mapping strategies WD352 / VD3521.0

Notes:
oy si

With the JPA tools in the Application Developer product, you can use wizards to create and
automatically initialize mappings. You can create new database tables from existing entity
u

classes (top-down mapping) or new entity beans from existing database tables (bottom-up
cl

mapping). You can also use the tools to create mappings between existing database tables
and entity beans (meet-in-the-middle mapping), where names or other attributes differ.
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Example Entity bean from the library case study


@Table(schema="LIBRARY", name = "AUTHOR")
@Entity
public class Author implements Serializable {
private static final long serialVersionUID = 1L;

.I. n
public Author() {super(); }
@Id
@Column(name = "AUTHOR_KEY")

.T ci
private int authorKey;
@Embedded
private PersonsName authorName;

.
public PersonsName getAuthorName() {return authorName; }
public void setAuthorName(PersonsName authorName) {

C
this.authorName = authorName;}

.F a
@ManyToMany
@JoinTable(name = "BOOK_AUTHOR", schema="LIBRARY"

C rm
joinColumns = @JoinColumn(name = "AUTHOR_KEY"),
inverseJoinColumns = @JoinColumn(name = "BOOK_KEY"))
private Set<Book> bookCollection;
public int getAuthorKey() { return this.authorKey; }
public void setAuthorKey(int authorKey) {
to fo
this.authorKey = authorKey; }
public Set<Book> getBookCollection() { return
this.bookCollection; }
public void setBookCollection(Set<Book> bookCollection)
this.bookCollection = bookCollection; }
}
ec vo

Copyright IBM Corporation 2008

Figure 8-3. Example Entity bean from the library case study WD352 / VD3521.0

Notes:
oy si

The entity above maps to a able called AUTHOR that has three fields: AUTHOR_KEY,
FIRST_NAME and LAST_NAME. As you can see the Entity bean looks very different. It
u

has three fields: authorKey, authorName, and bookCollection.


cl

This presentation explains how the mapping is defined. Specifically it describes the
annotations in the code above.
Ex
pr

8-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Using annotations and deployment descriptors


Object-relational mapping can be completely specified with
annotations or deployment descriptors or a combination.
The deployment descriptor is called orm.xml by default.

.I. n
Must reside in folder META-INF
To specify another mapping file, include a

.T ci
<mapping-file> element in persistence.xml
You can have several mapping files.

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

.F a
<entity-mappings >
<package>com.ibm.examples</package>

C rm
<entity class="com.ibm.examples.Employee" name="Employee">
<table name="EMPLOYEE"/>
<attributes> <id name="id"/>
<basic name="name">
to fo
<column name="EMPLOYEE_NAME" length="100"/>
</basic>

ec vo

Copyright IBM Corporation 2008

Figure 8-4. Using annotations and deployment descriptors WD352 / VD3521.0

Notes:
oy si

When you specify object-relational mappings using the JPA tools, the mapping information
is contained in the Java class files in the form of Java annotations.
u

However, you can also choose to define the object-relational mappings in XML in a file
cl

called orm.xml.
Mapping information defined in the orm.xml file automatically overrides both default JPA
Ex

behavior and any mappings defined using annotations. Therefore, you can, for example, to
adapt existing JPA entity beans to a different set of database tables without needing to
modify the entity class files.
In this unit you will focus on the creation of object-relational mappings using annotations in
pr

the entity class files.


In this example orm.xml file, the attributes of the entity-mappings are omitted to save
space. The full version is (one line is split to fit the printed page):
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

8-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Controlling JPA assumptions: Schema attributes


By default, JPA providers assume that:
Entity names correspond to database tables of the same name
Data member names correspond to database columns with the same

.I. n
names
Use annotations to override this default behavior or to fine-tune

.T ci
the relationship between object and data models:

.
@Table (name = "", schema="")

C
Controls underlying table name (not case sensitive)

.F a
Optional attributes specify database table and schema name

C rm
@Column (name ="")
Controls underlying column names (not case sensitive)
Other optional attributes, with default in bold:
nullable=true|false unique=true|false
to fo
Length=255 table="" (other than primary)
updatable=true|false insertable=true|false
scale=0 precision=0
columnDefinition="" (SQL fragment for generating DDL)
ec vo

Copyright IBM Corporation 2008

Figure 8-5. Controlling JPA assumptions: Schema attributes WD352 / VD3521.0

Notes:
oy si

Additional annotations are:


u

@SecondaryTable and @SecondaryTables to allow information from one entity to be


spread over several tables
cl

@JoinColumn and @JoinColumns to override choice of join columns


@PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns to allow foreign keys in
Ex

one table to have a different name from primary key columns in the referenced table
@JoinTable to override the JoinTable name
@UniqueConstraint forces a column to contain only unique values
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Data types allowed in persistent fields


JPA providers automatically configure basic mappings for most
Java primitive types, wrappers of the primitive types, and enums

.I. n
Persistent fields or properties must be of the following Java
language types:

.T ci
Java primitive types
Such as byte, int, float ...

.
Serializable types, including:

C
.F a
String
Primitive wrapper types

C rm
Collections of serializable types
User-defined types
Enumerated types
to fo
Embeddable classes:
Use annotation @Embedded when a set of fields is in a separate
class
ec vo

Copyright IBM Corporation 2008

Figure 8-6. Data types allowed in persistent fields WD352 / VD3521.0

Notes:
oy si

Most default mappings are as in JDBC:


u

VARCHAR and CHAR to String


INTEGER to into
cl

NUMERIC and DECIMAL to java.math.BigDecimal


Ex

REAL to float
DOUBLE to double
BIT to boolean
pr

Embeddable classes and the annotations @Embedded and @Embeddable are discussed
later in this lecture. They can be used for:
Compound primary keys
Logical grouping of columns in a table

8-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty An example of an embedded class:


Several columns in a CUSTOMER table give address information (Street, State, Country
Zip, and so forth) and you want to represent an address as a separate Java class from
Customer class. You can create an embeddable class called Address. Then you can
embed the Address class in the Customer entity bean. Indeed you can embed the Address
class in other entity beans that map to tables with the same set of columns for address
information.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Annotations for data type mappings


Annotations override default behavior or fine-tune the mapping
between object data types and database data types:
@Basic: is the default

.I. n
Add attributes to allow lazy fetching and prohibition of nulls

.T ci
@Basic (nullable=true, fetch=FetchType.LAZY)
private String comments;
@Enumerated: for fields with value values that must be specific

.
ordinals or strings

C
.F a
@Enumerated (EnumType.STRING)
private EnumType type;

C rm
@Temporal: for use with java.util.date and java.util.calendar fields
@Lob: indicates that data should be persisted as a BLOB or CLOB
@Lob
to fo
private byte[] photo;
@Transient: indicates data that should not be persisted
@Transient
Private float subtotal;
ec vo

Copyright IBM Corporation 2008

Figure 8-7. Annotations for data type mappings WD352 / VD3521.0

Notes:
oy si

Putting no annotation on a field is equivalent to:


u

@Basic (nullable="", fetch=FetchType.EAGER)


One reason to add the annotation explicitly is for clarity or documentation.
cl

In the @Basic example in the figure, say the table has a field called comments, which may
be empty or very large. The effect of the @Basic annotation here is twofold:
Ex

Allow the bean to be persisted when the comments field has value null.
Fetch the rest of the bean without automatically loading the comments field. If the code
then accesses the comments field, it is loaded automatically. Thus lazy loading
pr

eliminates loading a large amount of data that may not be needed.


The default for @Enumerated is EnumType.ORDINAL, in which case the database
column contains integers.

8-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Using fields of types java.sql.Date, java.sql.Time and java.sql.TimesStamp is transparent.


The @Temporal annotation provides extra metadata for types java.util.Date and
java.util.Calendar.
Java types byte[] and Byte[] map to binary large objects, or BLOB columns. Java types
char[], Character[], and String map to CLOB columns.
The JPA persists any instance variable or property not annotated @Transient or declared
transient.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Primary keys
Every entity has a unique object identifier called the primary key
For example, account number, employee number, tax ID
The primary key enables clients to locate particular entity instances

.I. n
An entity may have either a simple or a composite primary key

.T ci
Simple primary keys correspond to a single persistent property or field
Use @Id annotation
Composite primary keys correspond to either a single persistent property or field,

.
or to a set of single persistent properties or fields

C
Composite primary keys must be defined in a primary key class

.F a
Composite primary keys are denoted with @EmbeddedId
or @IdClass

C rm
Properties and fields involved in a primary key must
be one of the following Java language types:
Java primitive types
Java primitive wrapper types
to fo
java.lang.String
java.util.Date
java.sql.Date
ec vo

Copyright IBM Corporation 2008

Figure 8-8. Primary keys WD352 / VD3521.0

Notes:
oy si

Never use floating point types in primary keys.


u

If you use a generated primary key, only integral types will be portable.
cl
Ex
pr

8-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Primary key class requirements


A primary key class is a public class with the following
characteristics:

.I. n
Only public or protected properties
public default constructor

.T ci
hashCode() and equals(Object other)
method implementations

.
Serializable

C
.F a
A composite primary key must either be:

C rm
Represented and mapped to multiple fields
or properties of the entity class
or
to fo
Added as an embeddable class to the
entity class
ec vo

Copyright IBM Corporation 2008

Figure 8-9. Primary key class requirements WD352 / VD3521.0

Notes:
oy si

If the primary key class is mapped to multiple fields or properties of the entity class, the
names and types of the primary key fields or properties in the primary key class must
u

match those of the entity class.


cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Identity annotations allow simple and compound keys


@Id
Indicates one simple field is the key for the entity bean
@IdClass

.I. n
Indicates the class which is used to manage a composite key

.T ci
@EmbeddedId
Indicates that a field or property is itself a composite primary key,
represented by a primary key class

.
C
.F a
@Entity @Entity
@IdClass(PhoneKey.class) public class PhoneAccount

C rm
public class PhoneAccount {
{ @EmbeddedId
@Id private String area; private PhoneKey phoneKey;
to fo
@Id private String number; private String subscriber;
private String subscriber; //
// }
}
ec vo

Copyright IBM Corporation 2008

Figure 8-10. Identity annotations allow simple and compound keys WD352 / VD3521.0

Notes:
oy si

In both cases of compound keys, the PhoneKey class is a separate class defined to have
the two fields, area and number. When implementing the separate key class, you must
u

provide an implementation of equals() and hashcode() to allow sorting and hashing


cl

operations.
Ex
pr

8-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Primary key class example


@IdClass(PhoneKey.class)
@Entity
public class PhoneAccount

.I. n
public class PhoneKey implements Serializable { {
public String area, number;
@Id private String area;

.T ci
public PhoneKey() {} @Id private String number;
public PhoneKey(String area, String number) { private String subscriber;
this.area = area;
this.number = number;

.
/* Methods */

C
public boolean equals(Object o) { }

.F a
if ( this == o ) {
return true;
}

C rm
if ( ! ( o instanceof Phonekey)) {
return false;
}
PhoneKey pk1 = (PhoneKey) o;
return ( area==null ? o.area==null : area.equals(o.area) &&
( number==null? o.number==null : area.equals(o.number);
)
to fo
public int hashCode() {
return (area+number).hashcode;
}
}
ec vo

Copyright IBM Corporation 2008

Figure 8-11. Primary key class example WD352 / VD3521.0

Notes:
oy si

This example shows a primary key class for a primary key which is the concatenation of
two fields, area and number, and, in the inset, a sample usage of this class. The hashing
u

algorithm is slightly flawed, since one might want the key ("416","413") to fall into a different
cl

bucket from the key ("41","6413"). However, the equivalence algorithm will treat these two
keys as different, and this will suffice to sort out any collisions. In this particular example it
does not matter, as area and number are assumed to be of fixed length.
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Embedded class
When a set of columns makes a logical unit, you can create a
separate Java class

.I. n
@Embeddable
public class PersonsName implements Serializable {

.T ci
@Column (name= "FIRST_NAME")
private String firstName;
@Column (name= "LAST_NAME")

.
private String lastName;

C
.F a
//
}

C rm
@Entity
@Table(name = "PATRON", schema = "LIBRARY")
public class Patron implements Serializable {
@Embedded
to fo
private PersonsName patronName;
//
}
ec vo

Copyright IBM Corporation 2008

Figure 8-12. Embedded class WD352 / VD3521.0

Notes:
oy si

The sample above is also taken from the library case study. Note that the Patron entity has
the same embedded class as the Author entity in the example on an earlier slide. Sharing
u

this embedded class works because both the AUTHOR table and PATRON table have
cl

fields called FIRST_NAME and LAST_NAME.


Ex
pr

8-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Collections in entities
Collection-valued persistent fields and properties must use the
supported Java collection interfaces:

.I. n
java.util.Collection
java.util.Set

.T ci
java.util.List
java.util.Map

.
Generic variants of these collection types may also be used

C
.F a
Collection-valued persistent fields

C rm
usually represent one-to-many or
many-to-many relationships
between entities
to fo
ec vo

Copyright IBM Corporation 2008

Figure 8-13. Collections in entities WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Overview of relationships
Department Employee Role

.I. n
Project Cubicle

.T ci
Multiplicity Directionality Most common implementation

.
C
One-to-one Unidirectional or Foreign key in table

.F a
Bidirectional Simple field in Java class

C rm
One-to-many Unidirectional Foreign key in table
Collection field in Java class

Many-to-one Unidirectional Foreign key in table


Simple field in Java class
to fo
Many-to-many Bidirectional Foreign keys in join table
Collection field in Java classes
ec vo

Copyright IBM Corporation 2008

Figure 8-14. Overview of relationships WD352 / VD3521.0

Notes:
oy si

1-M and M-1 are unidirectional. You need both sides of the pair if you want to make it
navigable from both sides.
u

M-M implies a lookup table.


cl
Ex
pr

8-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Graphical depiction of relationships


Department
1 0..* Employee
1 0..* Job
1
0..*

.I. n
0..* 1

.T ci
Project Cubicle

There is a bidirectional one-to-many

.
relationship between Department and Employee

C
.F a
Given an employee, you can find the department
Given a department, you can find the set of employees it contains

C rm
There is a unidirectional one-to-many relationship between Employee and Job
Given an employee, you can find the set of jobs in the history of that employee
There is a bidirectional many-to-many relationship between Employee and Project
Given an employee, you can find the set of projects worked on by that employee
to fo
Given a project, you can find the set of employees working on that project
There is a bidirectional one-to-one relationship between Employee and Cubicle
Given an employee, you can find the cubicle of the employee
Given a cubicle, you can find the employee who occupies that cubicle
ec vo

Copyright IBM Corporation 2008

Figure 8-15. Graphical depiction of relationships WD352 / VD3521.0

Notes:
oy si

For example, if the Employee entity has a persistent property that contains a job history, it
might have the following methods:
u

List<Job> getJobHistory() {};


cl

void setJobHistory(List<Job>) {};


The cardinality of each side of the relationship is represented n..m, where n is the minimum
Ex

allowed number of occurrences and m is the maximum allowed. If m is *, the maximum is


unbounded. If n = m, write simply n. If m > 1, the cardinality is considered "many".
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Annotations for multiplicity


Multiplicity refers to the way entities relate to each other. There
are four types of multiplicities, each with its own annotation
@OneToOne

.I. n
Each entity instance is related to a single instance of another entity

.T ci
Example: Every employee has a cubicle; no cubicle is shared
@OneToMany
An entity instance can be related to multiple instances of the other

.
entities

C
Example: A department can have many employees

.F a
@ManyToOne

C rm
Multiple instances of an entity can be related to a single instance of the
other entity
This is the opposite of a one-to-many relationship
Example: Many employees work in a single department
@ManyToMany
to fo
Entity instances can be related to multiple instances of each other
Example: Many employees can participate in one project. One employee can
be part of many projects
ec vo

Copyright IBM Corporation 2008

Figure 8-16. Annotations for multiplicity WD352 / VD3521.0

Notes:
oy si

One side of every relationship has the join column, or foreign key. That side is the owning
side and the other is the inverse side.
u

Ordinality, cardinality, and multiplicity are all terms that refer to the number of entities on
cl

each side of the relationship.


Ex
pr

8-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Direction of relationships
Relationships have an owning side that determines how the
persistence runtime updates the relationship in the database
The owning entity has a field or property that refers to the other entity

.I. n
The direction of a relationship can be either bidirectional or
unidirectional

.T ci
A bidirectional relationship has both an owning side and an inverse
side

.
A unidirectional relationship has only an owning side

C
.F a
Bidirectional relationships must follow these rules:
For many-to-many bidirectional relationships either side may be the

C rm
owning side
For one-to-many and many-to-one relationships, the many side is the
owner
For one-to-one relationships, the owner is the one containing a foreign
to fo
key reference to the other
The inverse side of the relationship must refer to its owning side by
using the mappedBy element of the multiplicity annotation
ec vo

Copyright IBM Corporation 2008

Figure 8-17. Direction of relationships WD352 / VD3521.0

Notes:
oy si

In a unidirectional relationship, only one entity has a relationship field or property that refers
to the other. There is no inverse, so there is no need for the mappedBy element.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Attributes of relationships
mappedBy
Designates the property or field in the inverse entity that is the owner
of the relationship

.I. n
fetch
Sets the strategy for retrieving data from the database

.T ci
FetchType.LAZY default for one-to-many, many-to-many
FetchType.EAGER default for one-to-one, many-to-one

.
cascade

C
.F a
Determines how cascadable operations are propagated over
relationships

C rm
By default no operations are cascaded
CascadeType.MERGE CascadeType.REMOVE
CascadeType.PERSIST CascadeType.ALL
CascadeType.REFRESH
to fo
Example of customers having several accounts:
@OneToMany (mappedBy="custNo",
fetch=FetchType.LAZY, cascade=CascadeType.REMOVE)
protected Set <Account> accounts;
ec vo

Copyright IBM Corporation 2008

Figure 8-18. Attributes of relationships WD352 / VD3521.0

Notes:
oy si

The first three bullets in the slide are enumerations which are specified as parameters of
the annotation.
u

FetchType indicates to the runtime whether the association should be lazily loaded or must
cl

be eagerly fetched. The EAGER strategy is a requirement on the persistence provider


runtime that the associated entities must be eagerly fetched. The LAZY strategy is a hint to
the persistence provider runtime that the associated entities are only loaded when they are
Ex

invoked.
CascadeType defines the set of cascadable operations that are propagated to the
associated entity.
pr

Recall:
merge(T entity) - Merge the state of the given entity into the current persistence context.
CascadeType.MERGE - Cascade merge operations.
persist(Object entity) - Make an entity instance managed and persistent.
CascadeType.PERSIST - Cascade persist operations.

8-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty refresh(Object entity) - Refresh the state of the instance from the database, overwriting
changes made to the entity, if any. CascadeType.REFRESH Cascade refresh operations.
remove(Object entity) - Remove the entity instance. CascadeType.REMOVE - Cascade
remove operations.
The value cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE,
REFRESH}.

.I. n
In the last example, when an employee is deleted all the telephone numbers belonging to
that employee are also deleted.

.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Examples of relationships from the library application


@Entity
@Table(name="BOOK", schema = "LIBRARY")
public class Book implements Serializable {
@Id

.I. n
@Column(name = "BOOK_KEY")
private int bookKey;

.T ci
private String isbn;
private String title;

.
private String publisher;

C
.F a
private int pages;

C rm
@OneToOne
@JoinColumn(name="ISBN", referencedColumnName="AB_ISBN")
private BookAbstract bookAbstract;

@OneToMany ( mappedBy="book" )
to fo
protected Set <Copy> copyCollection;

@ManyToMany(mappedBy = "bookCollection")
private Set<Author> authorCollection;
ec vo

Copyright IBM Corporation 2008

Figure 8-19. Examples of relationships from the library application WD352 / VD3521.0

Notes:
oy si

The Book entity is related to three other entities: BookAbstract, Copy, and Author. Each
relationship is of a different type. In the last two relationships, the mappedBy attribute
u

indicates that the other classes, Copy and Author respectively, own the relationship and
cl

therefore specify the join details. The Book class in on the inverse side of these
relationships.
The ManyToMany relationship in the Book class is the inverse of the ManyToMany
Ex

relationship from the Author class that you saw in an earlier example. Here is the
declaration of the bookCollection field of the Author class:
@ManyToMany
pr

@JoinTable(name = "BOOK_AUTHOR", schema="LIBRARY"


joinColumns = @JoinColumn(name = "AUTHOR_KEY"),
inverseJoinColumns = @JoinColumn(name = "BOOK_KEY"))
private Set<Book> bookCollection;

8-24 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The challenge of concurrency


In many applications:
Multiple clients access the same entities at the same time
Database operations occur in a transactional context

.I. n
.T ci
.
Unrestricted access to rows in database tables can lead to:

C
.F a
Dirty reads
User A modifies a row in a transaction that remains active
User B fetches the same row and gets updates that A may roll back

C rm
Non repeatable reads
User A fetches an row in a transaction that remains active
User B modifies or deletes the same row and commits
User A rereads the row and finds it has changed or been deleted
to fo
Phantom reads
User A selects of rows in a transaction that remains active
User B inserts rows that match the select condition and commits
User A repeats the select and finds new rows
ec vo

Copyright IBM Corporation 2008

Figure 8-20. The challenge of concurrency WD352 / VD3521.0

Notes:
oy si

Transactions are covered in detail in unit 11 of this course. For now, consider them to be
logical units of work that must be performed on an all-or- nothing basis. When the
u

transactional context closes, all updates to the database are either committed or made
cl

permanent or rolled-back so that the database reverts to the state it was in prior to the start
of the transaction. While the transaction is active, the database is in a uncertain state.
Consider the following scenario:
Ex

Joe books an ticket for a flight and reserves the last seat on the plane. Before Joe pays,
and therefore commits the purchase transaction, Ann tries to book a seat on the same
flight. Should Ann be told that the flight is full that one seat is still available?
pr

For every application, the best solution comes down to analyzing the probability,
recoverability, and risk in such situations.

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Database aids for data consistency


Rational Database Management Systems (RDMBs) provide
locking mechanisms to isolate access to data
Read lock and write locks with RDMBs-specific variations

.I. n
Varies depending on specific database

.T ci
Isolation levels are locking strategies

Isolation level Dirty read Nonrepeatable Phantom read

.
read

C
.F a
Serializable Prevented Prevented Prevented

C rm
Repeatable Prevented Prevented Possible
read
Read Prevented Possible Possible
to fo
committed
Read Possible Possible Possible
uncommitted
ec vo

Copyright IBM Corporation 2008

Figure 8-21. Database aids for data consistency WD352 / VD3521.0

Notes:
oy si

The table above show how isolation levels apply database locks to prevent inconsistent
data.
u

Serializable lets only one transaction access a row at a time and prevents dirty reads,
cl

nonrepeatable reads, and phantom reads.


Repeatable read allows some concurrency and prevents dirty reads and
Ex

nonrepeatable reads but phantom reads are still possible


Read committed allows more concurrency but prevents only dirty reads
Read uncommitted provided minimal isolation and all three types of problems can
occur
pr

OpenJPA and therefore WebSphere Application server support all four of the above
isolation levels plus:
Default Uses the default level of the RDMBS JDBC driver
None provided no transaction isolation

8-26 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

The concurrency balancing act


Serialization means total isolation and 100% data consistency
Often results in poor performance

.I. n
No locking maximizes performance

.T ci
Can result in corrupt data

Locking strategies fall into two categories

.
C
Optimistic locking

.F a
Minimize time data is locked
Especially valuable in long-running transactions

C rm
Obtain read lock immediately before read and release immediately after
Obtain update lock before update and hold to end of transaction
Roll transaction back only if data updated by another transaction
to fo
Pessimistic locking
Holds all locks to end of transaction
Serializes (does not block) data access
ec vo

Copyright IBM Corporation 2008

Figure 8-22. The concurrency balancing act WD352 / VD3521.0

Notes:
oy si

Concurrency is an advanced topic and is closely related to transactions. However, the


following slides provide an overview of OpenJPA support for optimistic locking.
u

Configuration for pessimistic locking is beyond the scope of this course.


cl

For more detail, see the WebSphere Application Server Information Center.
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Managing concurrency with JPA


OpenJPA supports optimistic locking only.
WebSphere provides extensions:

.I. n
Use the LockManager plug-in to set up pessimistic locking
JPA Access intent allows finer control for pessimistic locking on DB2

.T ci
Optimistic concurrency ensures that:
Updates or deletes are consistent with the current state of the

.
C
database

.F a
Intervening updates are not lost
If committing a transaction commit would break these constraints:

C rm
The transaction is rolled back
An OptimisticLockException is thrown
to fo
Best Practice:
Enable optimistic locking for all entities that may be concurrently
accessed or merged from a disconnected state
ec vo

Copyright IBM Corporation 2008

Figure 8-23. Managing concurrency with JPA WD352 / VD3521.0

Notes:
oy si

The reason for using optimistic locking is to allow concurrent accessed to entities at the
same time as preventing an inconsistent entity state, lost updates, and other state
u

irregularities.
cl

The optimistic aspect is the assumption that resolving conflicts at commit time is safe. In
other words, the application must recover from rolled back transactions and exceptions of
type OptimisticLockException.
Ex

Optimistic locking essentially accepts the first commit request from a set of concurrent
transactions and rolls the other transactions back. Thus the first concurrent transaction to
commit wins.
pr

8-28 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Optimistic locking requires a version property


To enable optimistic locking for entities:
Entities must declare an property with name version
Property version must be:

.I. n
Typed: int, Integer, short, Short, long, Long, or Timestamp

.T ci
Annotated @Version or specified in persistence.xml
Mapped to column in the primary table to which the entity is mapped
@Entity

.
Public class Account implements Serializable {

C
@Version

.F a
@Column(name="OPTLOCK")
private int version;
protected int getVersion() {return versionNum;}

C rm
}

The persistence provider accesses or sets version


While performing life cycle operations on the entity instance
to fo
When the object is written to the database
Merge operation also checks version
Merging a stale copy throws an OptimisticLockException
ec vo

Copyright IBM Corporation 2008

Figure 8-24. Optimistic locking requires a version property WD352 / VD3521.0

Notes:
oy si

In this example the version attribute is mapped to database column called OPTLOCK. If
column name is not specified; it defaults to the property or field name.
u

An entity may access the state of its version field or property but must not modify the
cl

version value.
If the object being merged is a stale copy of the entity, this means that the entity has been
Ex

updated since the entity became detached. Depending on the implementation strategy
used, it is possible that this exception may not be thrown until flush() is called or commit
time, whichever happens first.
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Implementing optimistic locking


Include the version property in your entities and tables.
Do not change the version property from the application

.I. n
Use the openjpa.LockManager plug-in in WebSphere

.T ci
Make sure LockManager is set to version (the default)

openjpa.LockManager = version;

.
C
Make sure the database isolation level is read committed (the default)

.F a
or a vendor equivalent in which long-term read locks are not held

C rm
openjpa.TransactionIsolation=Read_committed;

Set the LockMode API for the EntityManager to guarantee


to fo
repeatable read on a per entity instance, if needed:
EntityManager.setLock(LockMode.READ); or
EntityManager.setLock(LockMode.WRITE);
ec vo

Copyright IBM Corporation 2008

Figure 8-25. Implementing optimistic locking WD352 / VD3521.0

Notes:
oy si

As a rule of thumb, adopt strategies in this order:


u

1. Use optimistic locking when entities may be accessed concurrently or detached and
then merged
cl

2. If frequent OptimisticLockException exceptions occur because transactions are rolled


back try pessimistic locking.
Ex

3. If you encounter frequent deadlocks, you can modify your pessimistic locking to use
serializable isolation level and to obtain a write lock for every read.
pr

The locking strategy can be specified in code, as shown above, or in persistence.xml, as in:
<persistence >
<persistence-unit name=example transaction-type=JTA>

8-30 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty <properties>
<property name=openjpa.LockManager value=version />
<property name=openjpa..jdbs.TransactionIsolation
value=read-committed />

</properties>

.I. n
</persistence-unit>

.T ci
</persistence>

.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Additional JPA locking strategies


In some situations, you need explicit read or write locks on
versioned entities

.I. n
When Isolation level read committed is not enough
Call the EntityManager.lock() method

.T ci
lock( entity, LoadModeType.READ | lockModeType.WRITE )

Two lock mode types are defined:

.
C
LockModeType.READ prevents dirty reads and non-repeatable reads

.F a
Example: Your application generates reports, and you do not want other
users updating entities when you are reading them to populate the report

C rm
LockModeType.WRITE prevents dirty reads, non-repeatable reads,
and checks for update conflicts
The persistence provider increments the version column when the
to fo
transaction commits or rolls back
No UPDATE or DELETE allowed from other transactions
ec vo

Copyright IBM Corporation 2008

Figure 8-26. Additional JPA locking strategies WD352 / VD3521.0

Notes:
oy si

With a WRITE lock, the persistence provider will generate an OptimisticLockException if


another user tries to update the locked entity from a separate transaction.
u

LockModeType.WRITE is useful when you are trying to manage relationships between two
cl

entities that may be updated in different transactions and you want to avoid
inconsistencies.
Ex
pr

8-32 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Application Developer persistence mapping tools

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 8-27. Application Developer persistence mapping tools WD352 / VD3521.0

Notes:
oy si

This course uses Rational Application Developer V7.5. This figure is taken from the JPA
perspective of Application Developer. The lower part of the figure shows the JPA Details
u

view with a field in the @JoinColumn annotation selected in Book.java source of the editor.
cl

The JPA details help create entity beans by generating annotations and attributes
according to mappings you specify selecting a table, a column, and properties of
relationships.
Ex

The JPA perspective also has Data Source Explorer view for viewing database schema
and table contents.
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Object-relational design strategies revisited


Top-down is good for pre-existing applications
Design object model first; let JPA generate data
Object
Simple: may require no more than @Entity and design

.I. n
@Id annotations
Choose mapping strategies based strictly on

.T ci
performance
Bottom-up is good for pre-existing databases

.
Design relational model first; design objects to

C
mimic relations

.F a
May miss opportunities to take advantage of
polymorphism and inheritance Relational

C rm
Meet-in-the-middle is required when design
applications and databases both already exist
May require heavy use of schema attribute annotations
to fo
@Table, @Column, @JoinColumn, ...
May force compromises. For example:
If the application relies on polymorphism, the database
may need to add or change column definitions
ec vo

Copyright IBM Corporation 2008

Figure 8-28. Object-relational design strategies revisited WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

8-34 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint (1 of 2)
1. When must you annotate a field or property in an entity
bean with @Column?

.I. n
.T ci
2. If the Order entity is in a one-to-many relationship with the
OrderItem entity, and both tables have a field OrderID:

.
a) Which bean is owner of the relationship and which is the

C
inverse?

.F a
b) Where and how do you use annotations to specify the

C rm
foreign key?
c) How do you ensure the orderItems are all deleted if the
order is removed from the system?
to fo
d) Can the relationship be bidirectional?
ec vo

Copyright IBM Corporation 2008

Figure 8-29. Checkpoint (1 of 2) WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

b)

c)
pr

d)

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Checkpoint (2 of 2)
3. Name a situation where more than one Java class may map
onto one database table

.I. n
4. In a many-to-many relationship, what are the roles of the join

.T ci
columns?

.
C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 8-30. Checkpoint (2 of 2) WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex
pr

8-36 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Unit summary
Having
Havingcompleted
completedthis
thisunit,
unit, you
youshould
shouldbe beable
ableto:
to:
Select
Selectthe
theappropriate
appropriatemapping
mapping strategy
strategy

.I. n
Use
Useannotations
annotationsforforschema
schemaand andtable
tablemappings
mappings
Use
Useannotations
annotationsforfor field
fieldand
andrelationship
relationship mappings,
mappings, including
including

.T ci
primary
primary key
keyclasses
classesandandembedded
embeddedclasses
classes
Define
Define one-to-one, one-to-many, many-to-one,and
one-to-one, one-to-many, many-to-one, andmany-to-
many-to-

.
many
manyrelationships
relationships

C
.F a
Describe
Describesome
someofofthe
thechallenges
challengesinvolved
involvedininconcurrency
concurrencyofof
data
dataaccess
access

C rm
Describe
Describetechniques
to fo techniquesused usedto tomanage
manageconcurrency
concurrencyininJPA
JPA
ec vo

Copyright IBM Corporation 2008

Figure 8-31. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 8. Object-relational mapping with JPA 8-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

8-38 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Unit 9. Java Persistence Query Language (JPQL)

What this unit is about


Java Persistence Query Language is a language for expressing
database queries in terms of JPA classes and properties of those

.I. n
classes. You will learn how to code JPQL queries.

.T ci
What you should be able to do
After completing this unit, you should be able to:

.
C
Create select, update, and delete operations on database tables in

.F a
Java Persistence Query Language

C rm
Explain the difference between JPQL and SQL
Create and use static and dynamic queries
Process the results of queries
to fo
Describe the implications of bulk updates using JPQL

How you will check your progress


ec vo

Checkpoint
Exercise
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit objectives
After
Aftercompleting
completingthisthisunit,
unit,you
youshould
shouldbebeable
ableto:
to:
Create
Createselect,
select,update,
update,and
anddelete
deleteoperations
operationson
ondatabase
database

.I. n
tables
tablesin
inJava
JavaPersistence
PersistenceQuery
QueryLanguage
Language
Explain
Explain the difference between JPQLand
the difference between JPQL andSQL
SQL

.T ci
Create
Createand
anduse
usestatic
staticand
anddynamic
dynamicqueries
queries
Process
Processthetheresults
resultsofofqueries
queries

.
Describe
Describethetheimplications
implicationsof ofbulk
bulkupdates
updatesusing
usingJPQL
JPQL

C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 9-1. Unit objectives WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

9-2 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Java Persistence Query Language


JPQL is a query specification language:
Part of the JPA API
Syntax derived from SQL

.I. n
Has a strong resemblance to EJB QL of the EJB 2 specification

.T ci
Tied to the entity object model, not the database schema
Not tied to a specific persistence implementation
Portable across different persistence providers and data sources

.
Operates on classes, properties, or fields

C
.F a
SQL JPQL

C rm
SELECT * FROM EMPLOYEE; select e from Employee e

Can navigate object relationships


Can be polymorphic with entities in inheritance hierarchies
Syntax can be much simpler than multi-join queries in SQL
to fo
Has an explicit join syntax
Full support for SQL-like select, update, and delete
Use entity manager for create
ec vo

Copyright IBM Corporation 2008

Figure 9-2. Java Persistence Query Language WD352 / VD3521.0

Notes:
oy si

The idea of EJB QL is to provide a way of specifying a query that depends only on the
EJBs and the relationships between them, not on the underlying database representation.
u

When the support code is generated, the EJB QL can be converted to the specific
cl

language for the database, such as SQL.


EJB QL is defined in Chapter 11 of the Enterprise JavaBeans Specification, Version 2.1.
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Select queries retrieve data


A JPQL select query consists of at least two clauses:
A select clause
Determines the type of the objects to be selected

.I. n
A from clause
Designates the domain for the select and where clauses

.T ci
An optional where clause
May be used to restrict the results returned by the query

.
An optional order by clause

C
May be used to arrange results in ascending or descending order

.F a
An optional group by clause
Sets a grouping expression for aggregating results

C rm
An optional having clause
Provides a filter to apply after grouping, like a secondary where
The where clause can contain a subquery, a select within a select:
to fo
select e from Employee e where e.salary =
(select max(e.salary) from Employee e)
The results may be collections, single objects, or an aggregate value
ec vo

Copyright IBM Corporation 2008

Figure 9-3. Select queries retrieve data WD352 / VD3521.0

Notes:
oy si

The structure of a JPQL select statement is almost identical to an SQL statement. What is
different is the use of variable and entity bean names instead of table and column names.
u
cl
Ex
pr

9-4 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Example JPQL select queries on one table


Find out who works in building W8200:
select e from Employee e where e.building = 'W8200'
select e from Employee e order by e.building

.I. n
Equivalent SQL:
SELECT * FROM EMPLOYEE WHERE BUILDING = 'W8200';

.T ci
SELECT * FROM EMPLOYEE ORDER BY BUILDING;

Retrieve employees with lastname names starting Mc, where name is

.
an embeddable class that is embedded in Employee:

C
.F a
select e from Employee e where e.name.lastName like ('Mc%')
Equivalent SQL:

C rm
SELECT * FROM EMPLOYEE WHERE LAST_NAME LIKE 'Mc%';

Get employee serial number and social security numbers:


select e.serial, e.ssn from Employee e order by e.serial
to fo
Equivalent SQL:
SELECT SERIAL, SSN FROM EMPLOYEE ORDER BY SERIAL
ec vo

Copyright IBM Corporation 2008

Figure 9-4. Example JPQL select queries on one table WD352 / VD3521.0

Notes:
oy si

Note that strings are delimited by single quotation marks, as in SQL. This syntax rule is
very useful as you often specify a query in a Java String delimited by double quotation
u

marks.
cl

Apart from that fact, you must match Java class names exactly and should follow the
convention of naming variables with lowercase letters.
Ex

JPQL syntax is not case-sensitive. Some people like to put all the SQL-like keywords in
uppercase. Others reserve uppercase for functions like COUNT, IN, and LIKE.
Use the dot (.) notation, as in Java, to navigate from classes to instances and then over
relationships.
pr

When there are issues from Java code, the select queries usually return a value of type
List. All the queries on this page return an object of type List<Employee>. The last example
returns an object of type List<List> where there are two inner lists, both of type
List<String>.

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Examples of JPQL select queries on multiple tables


Retrieve all employees who are working on a project:
select distinct e from Employee e join e.projects p
where p.status = 'active'
select distinct e from Employee e

.I. n
where e.projects.status = 'active'
When issued from Java, return a value of type List<Employee>

.T ci
These two queries are equivalent
Retrieve all projects for employees in the services division:

.
select distinct p from Division d join d.employees
e join e.projects p where d.name='services'

C
.F a
select distinct p from Division d, Project p
where p = d.employees.projects and

C rm
d.name = 'services'
When issued from Java, return a value of type List<Project>
These two queries are equivalent
Count all employees in the USA or Canada:
select count(e) from Employee e
to fo
where e.geo.region = 'Americas' and
e.geo.country in ('US','CA')
When issued from Java, returns a value of type int
ec vo

Copyright IBM Corporation 2008

Figure 9-5. Examples of JPQL select queries on multiple tables WD352 / VD3521.0

Notes:
oy si

You can use either of two notations to navigate across relationships, the join operator or the
dot (.) notation. You can even mix these notations in the same query.
u

You can chain the join and dot operators to navigate across multiple relationships as in the
cl

second group of examples.


In the following query, the expression p=d.employees.projects is necessary because
Ex

there is no direct relationship between projects and divisions in the object model.
select distinct p from Division d, Project p
where p = d.employees.projects and 'd.name=services'
A complete discussion of joins exceeds the scope of this course, where all joins are inner
pr

joins. Outer joins and fetch joins are also possible.


Outer joins are used when the data on one side of the join may not be available. For
example, use an outer join to retrieve all employees by department but allow some
employees to have no department assigned.

9-6 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty Fetch joins can help optimize database access by specifying that lazy loaded fields
should be prefetched.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JPQL reference information


Four types of queries are select, aggregate, update, and delete
Aggregates are selects that group results and produce summary data
Aggregates and select queries are called report queries

.I. n
Path expressions navigate entity relationships or to properties using the
dot notation

.T ci
select e from Employee e where e.name.firstname = 'John'

Constructor expressions return results in a user-specified object type

.
C
.F a
select new EmpInfo(e.Id, e.name, e.dept) from Employee e

Joins can be explicit with the JOIN operator or implicit through path

C rm
expressions in the where clause. One query can use both forms

Most common functions and operators from SQL are available


Operators: LIKE, BETWEEN, IN, ANY, ALL, SOME, and so forth
to fo
Function expressions: ABS,CURRENT_DATE, SUBSTRING, UPPER, and so
forth
Five aggregate functions: AVG, COUNT, MAX, MIN, SUM
ec vo

Copyright IBM Corporation 2008

Figure 9-6. JPQL reference information WD352 / VD3521.0

Notes:
oy si

Do not use the IN operator for joins. This legacy of EJB QL is deprecated.
u
cl
Ex
pr

9-8 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

JPQL supports two types of queries


Dynamic:
Provided by class javax.persistence.Query
Use with the EntityManager createQuery() method

.I. n
Supply the query as a String in the code:
Query q = em.createQuery("select e from Employee e");

.T ci
List<Employee> employees = q.getResultList();

Static or precompiled:

.
Use @NamedQuery annotation to define the query

C
.F a
Usually place in entity bean on which the query acts
Use with the EntityManager createNamedQuery() method

C rm
Typically, you call the query from the session bean, servlet, or class
that requires the data
@NamedQuery(name="findAllEmployees",
query="select e from Employee e")
to fo
Query q = em.createNamedQuery("findAllEmployees");
List<Employee> employee = q.getResultList();
ec vo

Copyright IBM Corporation 2008

Figure 9-7. JPQL supports two types of queries WD352 / VD3521.0

Notes:
oy si

The annotation @NamedQuery specifies a named query in the Java Persistence query
language, in which a static query is expressed in metadata.
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Creating named queries


Define named query in entity within the persistence unit
Usually in the file that defines the entity type

.I. n
Use annotations

.T ci
@NamedQuery (name="", query="") for one query
@NamedQueries ({ }) for a set of queries

.
@Entity

C
@Table(name="BOOK", schema="LIBRARY")

.F a
@NamedQueries ({
@NamedQuery (name="findAllBooks",

C rm
query="select b from Book b"),
@NamedQuery (name="getAuthorsOfBook",
query = "select a from Author a join
a.books b where b.bookKey = :bookKey" )
to fo
})
public class Book implements Serializable {
ec vo

Copyright IBM Corporation 2008

Figure 9-8. Creating named queries WD352 / VD3521.0

Notes:
oy si

The string defining the second named query in the listing above is shown spanning lines,
but in code must appear on one line.
u

In the second named query, the :bookKey indicates a named parameter.


cl
Ex
pr

9-10 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Queries with parameters


Both named and dynamic queries can be parameterized
Parameters can be positional

.I. n
Specify positional with a position index preceded by a ? (as in ?1)
Use with the setParameter(int position, Object value) method

.T ci
Query q = em.createQuery(
"select e from Employee e where e.dept = ?1");
q.setParameter( 1, "D782")

.
List<Employee> employees = q.getResultList();

C
.F a
Parameters can be named

C rm
Specify parameter name preceded by a colon (as in :deptId)
Use with the setParameter(String name, Object value)
@NamedQuery(name = "findAllEmployees",query =
"select e from Employee e where e.dept = :deptId")
to fo
Query q = em.createNamedQuery(findAllEmployees");
q.setParameter("deptId", "D782");
List<Employee> employee = q.getResultList();
ec vo

Copyright IBM Corporation 2008

Figure 9-9. Queries with parameters WD352 / VD3521.0

Notes:
oy si

The examples above show a positional parameter with a dynamic query and a named
parameter with a named query. You can use named parameters in both dynamic and
u

named queries.
cl

You can also use positional parameters in both dynamic and named queries, but named
parameters are usually preferred because they provide a measure of self-documenting
code.
Ex

One query can have several parameters.


The indexes on positional queries start at 1 and go up in increments of 1, as in
"select e from Employee where e.salary > ?1 and e.age < ?2 and e.startdate
pr

between ?3 and ?4"

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Queries with temporal parameters


JPQL, like JPA, handles temporal types from package java.sql
seamlessly; but temporal types from java.util need help

.I. n
When parameters have type java.util.Calendar or java.util.Date:
Use the enumeration TemporalType:

.T ci
Defines constants DATE, TIME, TIMESTAMP
Use overloaded Query method:
setParameter( int|String, Calendar|Date|Timestamp, TemporalType)

.
C
.F a
public list<Employee> getNewHires( Date jan01, Date dec31) {
Query q = em.createQuery ("select e from Employee e"

C rm
+ " where e.start between :start and :end" );
q.setParameter("start", jan01, TemporalType.DATE);
q.setParameter("end", dec31, TemporalType.DATE);
List<Employee> employees = q.getResultList();
for ( Employee e : employees ) {
to fo
// work with one employee record
}
}
ec vo

Copyright IBM Corporation 2008

Figure 9-10. Queries with temporal parameters WD352 / VD3521.0

Notes:
oy si

TemporalType.DATE maps to java.sql.Date.


u

TemporalType.TIME maps to java.sql.Time.


TemporalType.TIMESTAMP maps to java.sql.Timestamp.
cl
Ex
pr

9-12 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Processing query results


Choose your query method according to expected results:
A collection or set of records returned in a list

.I. n
List <Employee> employees = q. getResultList();

.T ci
A single entity

Employee employee = (Employee) q.getSingleResult();

.
C
.F a
Controlling the size of a result list:

C rm
Set the number of records to return

q.setMaxResults(25);
to fo
Set the position of the first record to return

q.setFirstResult(51);
ec vo

Copyright IBM Corporation 2008

Figure 9-11. Processing query results WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Update and delete queries


To update and delete individual entities, use the methods
EntityManager.persist and EntityManager.remove

.I. n
You can perform bulk updates to insert or delete several rows
at once by using JPQL update and delete statements

.T ci
Bulk updates and deletes bypass the entity manager

.
C
.F a
persist

C rm
remove

Data source
to fo
Persistence context

update or delete
ec vo

Copyright IBM Corporation 2008

Figure 9-12. Update and delete queries WD352 / VD3521.0

Notes:
oy si

Warning: If you are using JPQL for bulk updates, it bypasses the EntityManager, so your
persistence context may be out of synch with your database. After running the bulk update,
u

you should run the EntityManager refresh() method.


cl
Ex
pr

9-14 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Running bulk updates


delete and update statements have similar syntax to select
Use them to perform bulk updates on multiple records

.I. n
Use with the Query.executeUpdate() method
Return value has int and value = number of rows affected

.T ci
Query q = em.createQuery( "update employee e set " +
"e.dept=:newDeptCode where e.dept = :oldDeptCode" );

.
q.setParameter("oldDeptCode", "Millinery");

C
q.setParameter("newDeptCode", "Hats");

.F a
int count = q.executeUpdate();

C rm
Query q = em.createQuery( "delete Employee e where" +
"e.status = retired'");

Considerations:
to fo
The executeUpdate() method does not update persistence context
In-memory entities may be invalidated, depending on the persistence
provider
This may have a cascading impact on relationships
ec vo

Copyright IBM Corporation 2008

Figure 9-13. Running bulk updates WD352 / VD3521.0

Notes:
oy si

The last point on this page is important. It refers to the cascade and fetch attributes you can
place on relationships defined by annotations described in the unit Object relational
u

mapping with JPA.


cl

@One-to-one
@One-to-many
Ex

@Many-to-one
@Many-to-many
The recommended practice for bulk updates is to run them in a separate transaction of
pr

their own, or first in a larger transaction. For examples of what can go wrong, consider the
following scenarios:
A transactional method creates a new entity and calls persist on the entity manager,
making the new entity a managed entity. Later in the same method, the new entity is
deleted as the result of a bulk delete and removed from the database. When this
transaction exists, the application thinks that the entity is stored, but it is not.

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

A transactional method finds an entity and modifies some of its fields through the
managed entity. A bulk update also modifies some fields in the associated row in the
database. When the transaction commits, the entity image in memory has no record of
the changes made by the bulk update.

.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr

9-16 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Review of the Query interface


1. Create the query with:
EntityManager.createQuery(String) for dynamic queries
EntityManager.createNamedQuery(String) for static queries

.I. n
2. Set each parameter with:
One of the overloaded Query.setParameter() methods

.T ci
3. Optional: to page through a large number of records, use methods
Query.setFirstResult(int)

.
Query.setMaxResuls(int)

C
.F a
4. Optional: to override the default flush mode, AUTO
Query.setFlushMode(COMMIT)

C rm
5. Execute one of the methods:
Query.getResultList() for a select that returns multiple a list
Query.getSingleResult() for a select that returns one object
Query.executeUpdate() for update or delete bulk updates
to fo
6. Process the results
Cast the result from Query.getResultList() to the appropriate
List <type>
ec vo

Copyright IBM Corporation 2008

Figure 9-14. Review of the Query interface WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Using SQL queries (introduction to native queries)


SQL queries are also known as native queries

.I. n
You may want to issue SQL queries because:
Some complex queries can be performed efficiently only in SQL

.T ci
You can use simple stored functions with a native SQL query
JPQL has limitations:
JPQL cannot do recursive joins

.
C
.F a
The JPA provider uses JDBC to execute SQL
JPA does not update the persistence context or entities in memory

C rm
You should avoid SQL queries for INSERT, UPDATE, or DELETE

You can issue dynamic or precompiled SQL


to fo
JPA does not support stored procedures
You cannot access stored procedures with SQL queries
ec vo

Copyright IBM Corporation 2008

Figure 9-15. Using SQL queries (introduction to native queries) WD352 / VD3521.0

Notes:
oy si

The recommended practice is not to use SQL if JPQL is adequate.


u
cl
Ex
pr

9-18 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Issuing dynamic SQL in a native query


Create the Query object with one of the entity manager methods:
EntityManager.createNativeQuery( String )
Supply the SQL statement in the String argument

.I. n
EntityManager.createNativeQuery( String, class )

.T ci
Supply the type of returned entities in the class argument

EntityManger.createNativeQuery( String, String )


Define entities to map the results with the @SqlResultSetMapping annotation

.
C
Specify the mapping in the second String argument

.F a
EntityManager em;

C rm
public List<Employee> getEmployeeById( String id) {
String sqlStatement =
"Select * from Employee where EmpId= ?1";
Query q = em.createNativeQuery( sqlStatement,
to fo
Employee.class);
q.setParameter( 1, id);
return q.getResultList();
}
ec vo

Copyright IBM Corporation 2008

Figure 9-16. Issuing dynamic SQL in a native query WD352 / VD3521.0

Notes:
oy si

The query in this example does not justify the use of a native query, but it serves to show
how to use native queries. The skill is in writing an efficient SQL statement that performs a
u

complex query. In this case, the method would be better written as:
cl

public getEmployeeById(String id) {


return em.find(Employee.class, id);
}
Ex
pr

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Issuing precompiled SQL in a native query


Define the SQL statement with an annotated field
Use @NamedNativeQuery to define the query
Create the Query object with the entity manager method:

.I. n
EntityManager.createNamedQuery( String )

.T ci
@PersistenceContext(unitName="EmployeeDB")
EntityManager em;

C
@NamedNativeQuery

.F a
name ="getEmployeeById",
query = "Select * from Employee where EmpId= ?1",

C rm
resultClass = com.ibm.examples.Employee.class)

public List<Employee> getEmployeeById( String id) {
Query q = em.createNamedQuery("getEmployeeById");
to fo
q.setParameter( 1, id);
Return q.getResultList();
}
ec vo

Copyright IBM Corporation 2008

Figure 9-17. Issuing precompiled SQL in a native query WD352 / VD3521.0

Notes:
oy si

As with dynamic SQL, you have the option to define a mapping with the
@SqlResultSetMapping annotation. If you use that approach, specify the name of the
u

mapping as an attribute of the @NamedNativeQuery annotation.


cl

Native queries are a large topic with at least as much complexity as JPQL.
Ex
pr

9-20 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
V5.2
Student Notebook

Uempty

Checkpoint
1. Write the select query to fetch all items in an order that cost
more than $10.

.I. n
2. State one advantage of a static query over a dynamic query.

.T ci
3. If a query has a parameter:
a) What method do you use to provide the actual value?

.
C
b) How do you specify the parameter in the query? Show two ways.

.F a
4. What annotation defines a static query, and where does it

C rm
go?

5. What method do you call to perform a bulk update?


to fo
6. Why do some programmers always run bulk updates in a
separate transaction from other database operations?
ec vo

Copyright IBM Corporation 2008

Figure 9-18. Checkpoint WD352 / VD3521.0

Notes:
oy si

Write your answers here:


u

1.
cl

2.
Ex

3.

b)
pr

4.

5.

Copyright IBM Corp. 2008 Unit 9. Java Persistence Query Language (JPQL) 9-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit summary
Having
Havingcompleted
completedthisthisunit,
unit, you
youshould
shouldbe
beable
ableto:
to:
Create
Createselect,
select,update,
update,and
anddelete
deleteoperations
operationson
ondatabase
database

.I. n
tables
tablesin
inJava
JavaPersistence
PersistenceQueryQueryLanguage
Language
Explain
Explainthe
thedifference
differencebetween
betweenJPQLJPQLand
andSQL
SQL

.T ci
Create
Createand
anduse
usestatic
staticand
anddynamic
dynamicqueries
queries
Process the results of queries
Process the results of queries

.
Describe
Describethetheimplications
implicationsof ofbulk
bulkupdates
updatesusing
usingJPQL
JPQL

C
.F a
C rm
to fo
ec vo

Copyright IBM Corporation 2008

Figure 9-19. Unit summary WD352 / VD3521.0

Notes:
oy si
u
cl
Ex
pr

9-22 Developing EJB3 Applications Copyright IBM Corp. 2008


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
CONTACTO
Telfono
91 761 21 78
Pngase en contacto con nuestro equipo y le
informaremos de cualquier duda o cuestin
que pueda surgirle.

Email
formacion@arrowecs.es
Mndenos un email y le atenderemos
enseguida.

Online
@Arrow_Edu_ES
O bien puede contactarnos a travs de
nuestro perfil en Twitter.

Vistenos
Arrow ECS Education Services
Avenida de Europa 21,
Parque Empresarial La Moraleja
28108 Alcobendas, Madrid

EDUCATION
S E R V I C E S

You might also like