Cloud Mobility
Intelligence Centre
Student Manual
CONSEJERA DE EMPLEO,
TURISMO Y CULTURA
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
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
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
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
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Ex
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
.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
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14
cl
.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
.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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
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
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:
.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
beans
cl
.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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
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
Day 4
Exercise 9: Importing a Web user interface to the library case study
Ex
Day 5
Exercise 12: Creating a Web service from a stateless session bean
(optional)
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
.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
Checkpoint
u
cl
Ex
pr
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
.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
Figure 1-3. A timeline: The evolution of the Java platform WD352 / VD3521.0
Notes:
oy si
As of October 2008:
u
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
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
.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
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
Uempty
.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
Notes:
oy si
Many of the API listed above are not mentioned again in this course.
u
cl
Ex
pr
.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
Notes:
oy si
Uempty
.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
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
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
.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
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
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.
Uempty
.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
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
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.
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
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
Notes:
oy si
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
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
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
Uempty
.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
Notes:
oy si
u
cl
Ex
pr
.I. n
To improve performance through load balancing
.T ci
Integrating independent systems to act as a single system
.
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
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.
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
Uempty
.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
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
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
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
.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
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
Notes:
oy si
Directory services
Object binding and lookup
cl
Acronyms:
LDAP: Lightweight Directory Access Protocol is a standard interface directory access
DNS: Domain Name Service
pr
Uempty
.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
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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
Uempty
.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
Notes:
oy si
This slide provides a review of what annotations do. You will recall that annotations were
introduced in Java SE 5.
u
.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
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
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
Uempty
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
Figure 1-22. Application files are packaged into archives WD352 / VD3521.0
Notes:
oy si
Contain source
Be opened with a zip utility
cl
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
Uempty
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
Notes:
oy si
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.
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
Uempty
.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
Notes:
oy si
Checkpoint
1. What are annotations?
.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
Notes:
oy si
1.
cl
2.
Ex
3.
4.
pr
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
Notes:
oy si
u
cl
Ex
pr
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
.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
Exercise
u
cl
Ex
pr
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
Notes:
oy si
Conceptually, this definition has not changed since the original EJB specification.
u
cl
Ex
pr
.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
Notes:
oy si
Uempty
.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
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
.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
Notes:
oy si
Uempty
.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
Notes:
oy si
u
cl
Ex
pr
.I. n
.T ci
Simplified persistence with object-relational mapping (ORM)
.
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
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).
Uempty
.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
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
.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
Notes:
oy si
u
cl
Ex
pr
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
Notes:
oy si
EJB 3.0 uses metadata annotations, that are part of Java SE 5.0.
u
deployment descriptors.
Annotations can be used by the compiler to generate boilerplate code.
Ex
.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
Uempty
.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
Notes:
oy si
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
.I. n
The object need not request these resources explicitly
.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
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
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.
Uempty
.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
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 .
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
Uempty
.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
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
.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
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
Uempty
.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
Notes:
oy si
Recall that one of the reasons for using EJBs is to get transactional support.
u
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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
Uempty
.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
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
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.
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
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
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
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
Notes:
oy si
EJBs are transactional by default: unless you override the default settings, all methods of
EJBs run in a transactional context.
u
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
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
.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
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
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.)
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
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
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
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
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
Notes:
oy si
1.
cl
2.
Ex
3.
pr
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
Notes:
oy si
u
cl
Ex
pr
.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
Checkpoint
cl
Ex
pr
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
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
.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
Notes:
oy si
Stateless
Every call is independent
cl
Stateful
Ex
Uempty
.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
Notes:
oy si
.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
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
Uempty
.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
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
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 { ... }
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
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
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
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
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
Uempty
.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
Figure 3-9. Example: Stateless session bean with remote interface WD352 / VD3521.0
Notes:
oy si
u
cl
Ex
pr
.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
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
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
Uempty
.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
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
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
Uempty
.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
Notes:
oy si
Thus, a bean that performs credit checks may have an interface named CreditChecker and
bean class named CreditCheckerBean.
pr
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
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
you specify Java Naming and Directory Interface (JNDI) names for the artifacts referenced
in an application.
Ex
pr
Uempty
.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
C rm
interfaces
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
/<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
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
Uempty
.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
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
.I. n
Ready
Destruction exist
.T ci
Client no longer needs bean
.
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
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
Uempty
.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
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
.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
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.
Uempty
.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
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
.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
Notes:
oy si
Checked exceptions are the ones you must list in the throws clause of a method.
u
subsystem
between the client and the container.
pr
Uempty
.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
Figure 3-21. Comparing stateful and stateless session beans WD352 / VD3521.0
Notes:
oy si
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
.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
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
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
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
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
Notes:
oy si
1.
cl
2.
Ex
3.
4.
pr
5.
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
Notes:
oy si
u
cl
Ex
pr
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
oy si
u
cl
Ex
pr
.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
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
Uempty
.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
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
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
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
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
Uempty
.I. n
.T ci
Borrow copy
extends
.
Return copy Browse catalog
C
.F a
extends
Reserve item
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
.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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
.I. n
Book
Catalog
.T ci
Manager
Author
.
Abstract DB
C
.F a
LoanManager
Copy
C rm Onloan
to fo
PatronManager Patron
Figure 4-7. Phase 3: Add interfaces to the entity beans WD352 / VD3521.0
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
.I. n
.T ci
Item Catalog
Reserver Manager
.
Web
C
app
.F a
Borrower LoanManager
C rm Returner
Patron
Manager
to fo
ec vo
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
Uempty
.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
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
.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
Notes:
oy si
u
cl
Ex
pr
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
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
.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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
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
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
Uempty
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
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
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
.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
Notes:
oy si
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
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
.
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
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
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
.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
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
online at http://junit.sourceforge.net/doc/cookbook/cookbook.htm
Uempty
.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
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
.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
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
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
Notes:
oy si
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
Notes:
oy si
u
cl
Ex
pr
.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
Exercise
u
cl
Ex
pr
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
Notes:
oy si
Web browsers.
DHTML (Dynamic HTML) consists of HTML mixed with JavaScript to provide client-side
Ex
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.
.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
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
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
Uempty
.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
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
.I. n
public class EJBClient {
.T ci
@EJB
MyEJBInterface myei;
protected void doWork () {
.
//
C
whatever = myei.myMethod(arg1, arg 2);
.F a
//
}
C rm
}
Notes:
oy si
Uempty
.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
Notes:
oy si
The @EJB notation occurs at field level. The EJB is not initialized explicitly because the
container provides it.
u
name: The logical name of the EJB reference within the declaring component's
(java:comp/env) environment (String)
Ex
.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
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.
Uempty
.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
Figure 6-8. Visualization of client interaction with session bean WD352 / VD3521.0
Notes:
oy si
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
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
.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>")
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
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
Notes:
oy si
.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
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
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
Uempty
Checkpoint
.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
Notes:
oy si
1.
cl
2.
Ex
3.
b)
pr
c)
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
Notes:
oy si
u
cl
Ex
pr
.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
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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)
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
.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
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
Uempty
.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
Notes:
oy si
The JPA implementation for WebSphere Application Server is built on the Apache
OpenJPA open source project.
u
extensions to provide additional features and utilities for WebSphere Application Server
customers.
Ex
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
.I. n
JPA entities are ordinary JavaBeans. They:
Are not remotely accessible
.T ci
Have a persistent identity distinct from their object reference
.
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
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
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.
Uempty
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
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
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
Uempty
.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
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
.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
Notes:
oy si
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
Uempty
.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
Figure 7-9. Example entity class for the simplest situation WD352 / VD3521.0
Notes:
oy si
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
.I. n
The entity manager maps this field to the primary key
.T ci
May be a instance of a key class
.
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
Notes:
oy si
Uempty
.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
Notes:
oy si
getProperty() and set method setProperty(). For example, if the Employee has a field
called name, the class defines getName() and setName().
Ex
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
.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
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
Uempty
.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
Notes:
oy si
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
.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
Uempty
.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
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
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
Uempty
.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
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
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
.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
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
persistence context.
Uempty
@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
Notes:
oy si
contains(): Check whether the entity instance belongs to the current context.
Ex
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
@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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
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
Notes:
oy si
Transaction scope:
The persistence context is transaction-scoped. Entity become detached when the
cl
transaction ends.
Extended scope
Ex
Uempty
.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
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
@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
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
Uempty
.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
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
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
.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
.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
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
Uempty
.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
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
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
Uempty
.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
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
.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
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
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
Uempty
.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
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
.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"); }
}
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.
Uempty
Checkpoint questions
1. Does the EJB 3 specification cover entity beans?
.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?
Notes:
oy si
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
Notes:
oy si
u
cl
Ex
pr
.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
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
.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
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
This presentation explains how the mapping is defined. Specifically it describes the
annotations in the code above.
Ex
pr
Uempty
.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
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
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
Uempty
.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
Notes:
oy si
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
.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
Notes:
oy si
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
.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
.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
Notes:
oy si
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
.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
Notes:
oy si
If you use a generated primary key, only integral types will be portable.
cl
Ex
pr
Uempty
.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
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
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
.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
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
operations.
Ex
pr
Uempty
.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
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
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
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
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
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
Uempty
.I. n
0..* 1
.T ci
Project Cubicle
.
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
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
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
.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
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
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
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
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
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.
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
.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
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
Uempty
.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
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
.I. n
Varies depending on specific database
.T ci
Isolation levels are locking strategies
.
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
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
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
Uempty
.I. n
No locking maximizes performance
.T ci
Can result in corrupt data
.
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
Notes:
oy si
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
.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
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
Uempty
.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
}
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
.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;
Notes:
oy si
1. Use optimistic locking when entities may be accessed concurrently or detached and
then merged
cl
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>
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
.I. n
When Isolation level read committed is not enough
Call the EntityManager.lock() method
.T ci
lock( entity, LoadModeType.READ | lockModeType.WRITE )
.
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
Notes:
oy si
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
Uempty
.I. n
.T ci
.
C
.F a
C rm
to fo
ec vo
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
.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
Notes:
oy si
u
cl
Ex
pr
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
Notes:
oy si
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
Notes:
oy si
1.
cl
2.
Ex
pr
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
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
.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
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
Notes:
oy si
u
cl
Ex
pr
Uempty
.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
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
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
.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
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
Uempty
.I. n
Equivalent SQL:
SELECT * FROM EMPLOYEE WHERE BUILDING = 'W8200';
.T ci
SELECT * FROM EMPLOYEE ORDER BY BUILDING;
.
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%';
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
.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
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
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
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
.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'
.
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
Notes:
oy si
Do not use the IN operator for joins. This legacy of EJB QL is deprecated.
u
cl
Ex
pr
Uempty
.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
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
.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
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
Uempty
.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
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
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
.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
Notes:
oy si
Uempty
.I. n
List <Employee> employees = q. getResultList();
.T ci
A single entity
.
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
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
.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
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
Uempty
.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
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
@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
Uempty
.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
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
.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
Figure 9-15. Using SQL queries (introduction to native queries) WD352 / VD3521.0
Notes:
oy si
Uempty
.I. n
EntityManager.createNativeQuery( String, class )
.T ci
Supply the type of returned entities in the class argument
.
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
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
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
.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
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
Native queries are a large topic with at least as much complexity as JPQL.
Ex
pr
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?
Notes:
oy si
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
Notes:
oy si
u
cl
Ex
pr
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