Java EE Foundations

n + 1, Inc

Copyright (c) v1.0.0 2010 n + 1, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ”GNU Free Documentation License”.

Page 2

c 2010 n + 1, Inc All Rights Reserved

Contents
1 Java EE Overview 1.1 Java EE Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.2 Servlets and Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . Java Transaction API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Java Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Java Naming And Directory Interface . . . . . . . . . . . . . . . . . . . . . . . JavaMail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Enterprise Java Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Java IDL / RMI / RMI-IIOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Java Messaging Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 14 14 15 16 17 18 19 20 21 22 23 24 25 27 29 30 33 34

Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.1 1.2.2 1.2.3 1.2.4 Creating A Customer Annotation . . . . . . . . . . . . . . . . . . . . . . . . . Associating Annotations With A Class . . . . . . . . . . . . . . . . . . . . . . . Multiple Value Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.3 2

Lab Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Session Beans 2.1 What Is A Session Bean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

CONTENTS 2.1.1 2.1.2 2.2 Stateless Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stateful Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 34 35 35 36 36 36 37 38 40 40 41 41 45 46 47 49 49 50 52 53 54 55 56 59 60 69

How Session Beans Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.1 2.2.2 2.2.3 Proxy / Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EJB Container Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bean Instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.3

Developing a Session EJB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3.1 2.3.2 Remote and Local Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . Session Bean POJO Implementation . . . . . . . . . . . . . . . . . . . . . . . .

2.4

Building EAR Deployment File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.1 2.4.2 2.4.3 Compiling With ANT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Packaging EJBs With ANT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.5

Accessing Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.5.1 2.5.2 JNDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Accessing Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.6

Life Cycle Of Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.1 2.6.2 Stateless Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . Stateful Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . .

2.7 3

Lab Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Entity Beans 3.1 What is an Entity Bean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1.1 3.1.2 3.2 Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entity Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Creating An Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2.1 Mapping to Database Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3.3 Page 4

Using An Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

c 2010 n + 1, Inc All Rights Reserved

4. . . . . 3. . Employee Manager Session Bean . . . . . . . . . . 125 c 2010 n + 1. . . . . .6 4. . . . . .1 3. . . . 121 Fetch Type . . . .1. Updating Data . . . . . . . . . .1 3. . . . . . . . . . . . . .4. . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 4. . . . . . . . .7 4 Ant Build Files . . . . . . 101 Many to One Unidirectional . .1. . . . . . . . . . One to Many Unidirectional . . . . . . . . Entity Beans 4. . . . . . . . . . . . . . . . . . . . . .3 Lists and Ordered By . . . . . . Finding Multiple Employees .4 4. . . . .3. . . . . . . 3. . .4 Obtaining The Entity Manager . . . . .6 3. . . . Removing Employees . . . . . . . . . . . Inc All Rights Reserved Page 5 . . . . . . . . .7 Employee Entity Bean . .1. . . . . . . . . .5. . . . . .3. . . . . .2 3. .6 3. . . . . . . .4. . . . . . . . . . . 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 3. . . . . . .1 Entity Bean Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . .1 4. . . . . . 4. . . . . . .1 4. . . . . . . . . . . . . . . . . Updating Employee . . . . . . . . . .1. . . . . .2 3. . . . . . . .5 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . One to One Bidirectional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entity Manager Methods .3 3. . . . . . . . . . . . . . Lab Activity . . . . . . .1. . 105 One to Many Bidirectional .1. . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . 3. .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Cascading Type . . . . . . . . . . . . . . . . . . . . . .4 3. . . . . . . .Java EE Foundations 3. . . . . . . . . Finding Employees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Persistence Units . .2 One to One Unidirectional . . .2 4. . . . . . . . .4. .2 4. . . 115 Multiple Relationship Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . . . .4. . . . . . . . . . . . 70 71 72 73 74 76 77 78 79 80 81 83 84 85 87 89 90 92 96 Example Session Bean to Manage Employee Entity . . . . . . . . . . . . . . . . . . . .5 DataSources . . . . . . . . . . . Adding New Employee . . . . . .3 3. . . . . . 111 Many to Many Relationships . . . . .3 4. . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 5. . . . . . . . . . . . . . . . . . . . 170 c 2010 n + 1. . . . . 162 Named Queries . . . .3 5. .CONTENTS 4. . . . . . . . . . . . . .2 WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . 126 4. . . . . . . . . . 128 137 Querying Entity beans 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Other Persistence Functionality . . . . . . .7 5. . . . . . . . . 140 Introduction to EJBQL . . . . 153 Other Operators . . . . . . . . . . 168 6. . . . . .4 Queries . . 126 Race Manager . . . . . . .1. . . . . . 156 Ordering Results . . . .2. . . . . .3 Paging Results . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . .1. . . . . . . . . . . . . . . . . 157 Aggregates .2.2 5.2. . . . . . .4 5. . . . . . . . . . . . . . . . . . 141 Navigating Objects . . . . .1 5. . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . 161 5. . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . 163 Native Queries .6 5. . . . . . . . . .2 5 Defining Entity Beans . . . . . . . . . . . . . . . . . . . . . . . 147 Dynamic WHERE Clause Values . 151 Like Operator . . . . . . . .3 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 5. . . . .2 5. . . . . . . . . . . .2.3. . . . . . . . . . . . . . 148 Comparison Symbols . . . . . . . . 139 Query Result Methods . . . . . . . . . 169 J2EE Container Provides Transaction Management . . . . . . . . . . . . . . . .3 Example Using Relationships . . . . . . . . . . . . . . . . . . . . . . . . . .8 EJBQL WHERE Clause . . . . . .5 5. . . . . . . . . . . . . . . . . .1. . . . 150 Logical Operators . . . . . . . . .3. . . . . . . 165 167 6 Transactions 6. . . .2. . . . . . . . . . . . . . . . . . . .1 6. . . . . . . . . . . . .1 Transactions . . . . . . . .2 5. 159 5. .1 4. . . . . . . . . Inc All Rights Reserved Page 6 . . . . .1 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Querying Entity Beans . . .2 ACID Transaction . . . . . . .2. 138 5. . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . 146 5. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . .1. . . . 201 7. . . . . . . . . . . .2 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Exceptions and Transactions . . . . . . . .1. . . . . . . .3. . . . . . . . . . .2 Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 7. . . . . . . . . . . . . . . . . . .4 6. . . . . . . . . . . . . 192 7. . . . . . . 204 Messaging MDB From Session Bean . . . . . . . . . . . . . . . . . . . . . .1. . 182 7. . . . . . . . . . . . . . . . . 205 207 8 JavaMail 8. . . . .2. . . . . . . . . . .4 Message Driven Beans . .1 7. . . . .4 Mail Session . . . . . 202 Deploying A Message Driven Bean . . 193 JMS Message Types . . . . . . . . .2 Message Delivery . . . . . . 180 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 7. . 173 Isolation Levels . . . . . . . .Java EE Foundations 6. . . . . . . . . . . .3 JMS Messages . . . . . . .2 8. . . . . . . . . . . . . . . .4. .1. . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . 208 8. . 209 Email Addresses . . . . . . . . . . . . . . . . . . . .1 7. . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 7.1 Java Messaging Service . . . . . .1 7. . . 176 179 JMS And Message Driven Beans 7. . . . . . . . . . . . . . . . .5 Message Interface . . . . 189 7. . . . . . . . . . . . . 211 Message Recipients . . . . . . . . . . . . . . . .3. 210 MIME Email Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . 184 Queues . . . . . .2 Publish / Subscribe . .1 JavaMail API . . . . . . . . . . . . . . . .3 Creating Message Driven Beans . . . . 181 Point to Point . . . .1. . . . . . . . 196 Receiving a JMS Message . .1. . . . . . . . . . . . . . Inc All Rights Reserved Page 7 . .5 7 Six Transaction Scopes . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . .1 8. . . . . . .4. . . . . .3. . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . .1 7. . . 199 7. 198 Using Listeners . . . . . . . . . . . . . . . . .3 6. . . . . . .2 7. . . . . .3 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 c 2010 n + 1. . . . . . . 194 Sending JMS Message . .

. 215 219 GNU Free Documentation License . 214 Attachments . . .1. . . . . . . . . .7 Appendices A Message Content . . . . .CONTENTS 8. . . 219 Page 8 c 2010 n + 1. . . . . . . . . 213 Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . .5 8. . . . . . . . . . . . . . . . . .6 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . Inc All Rights Reserved . .

. . . . . . . . . . . . . . . . .List of Tables 3. . . . . . . 151 Aggregate Functions . . . . . . . . . . . . . . . . .3 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 JMS Message Types . . . . . . . . . . .3 7. . . . . .1 7. . . . . . . . . . . 139 Query Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 3. . . .5 5. . . . . . . . . . . . . . . .4 5. . . . . . .4 Common EntityManager Methods . . . 193 JMS Properties . 176 Mapping Of Topic To Queue Equivalents . . . . . . . . . . . . . . . . . . . . 150 Logical Operators . . . . . . 125 EntityManager Query Methods . . . . . . . . . . . . . . .1 5. . . . . . . 140 Temporal Types . . . . . . . . . . . . . . . . . . . . . . 190 JMS Header Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 5. . Temporal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 7. . . . . . . . . .1 3. . . . . . .1 7. . . . . . . . . . . . . . . .2 5. . . . . . . . . . . . . . 149 Comparison Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Isolation Levels . .3 4. . . . . . . . . . . . . . 194 9 . . . .6 6. . . . . . . . . . . . . . . . . 59 66 71 Cascade Values . . . . . . . . . . . Common EntityManager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . .

Inc All Rights Reserved .LIST OF TABLES Page 10 c 2010 n + 1.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TimeSplit Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .List of Programs 1 2 3 4 Race Class . . . . . . . . . . . . . . . . . . . . . . . . . 132 133 134 135 11 . . . . . . . . . . . . . RaceManager Interface RaceManager Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

LIST OF PROGRAMS Page 12 c 2010 n + 1. Inc All Rights Reserved .

Chapter 1 Java EE Overview Objectives • Understand the basic components contained within Java EE framework • Understand what an annotation is • Learn how to create custom annotations 13 .

1. At this point it is important to note that Java Server Pages become compiled into servlets so they are treated identically as servlets within the servlet container. Page 14 c 2010 n + 1. 1. The browser then renders the HTML. JAVA EE OVERVIEW 1. Inc All Rights Reserved . The servlet engine takes the incoming HTTP request and transforms it into a HttpServletRequest object to be handled by the servlets. The focus of Java EE is to provide enterprise quality middleware services that allow the developers to focus on the business logic of the application and not the development infrastructure. This allows applications to quickly scale with less work from developers. The JSP and servlets provide a web based presentation layer for business applications. The resulting response is encapsulated within a HttpServletResponse object. The HttpServletResponse contains the data being sent back to the client.1 Servlets and Java Server Pages Servlets and Java Server Pages provide dynamic content for web servers and are an entry point into the entire Java EE environment. The servlet engine takes the HttpServletResponse and translates it into a HTTP Response which is returned to the browser.CHAPTER 1. The web server can be any of the main web servers such as Apache and IIS.1 Java EE Overview Java EE (Java Enterprise Edition) is a set of integrated services that allow developers to quickly create enterprise quality solutions. The web server takes the HTTP request and passes it along to the servlet container. The servlets then use access to the Java EE environment to apply business logic to the incoming request. Client browsers send a HTTP request to the web server requesting a particular JSP or servlet.

2 Java Transaction API The JTA provides an API for easily creating and managing transactions within the Java environment. Atomic commands within a transaction either all succeed or all fail. Inc All Rights Reserved .1. Thus they can not step on each others toes. One of the features that Java EE containers provide is integration of the JTA with Enterprise Java Beans.Java EE Foundations 1. Durable Once a transaction is committed the the update will survive even if the system fails. It supports start. Making it a trivial process to set up transaction capabilities for methods associated with enterprise beans. and rollback actions necessary for ACID compliant transactions. abort. commit. Page 15 c 2010 n + 1. Consistency the state of the database is in a consistent state at all times Isolation transactions are isolated from one another.

CHAPTER 1. Each database provides a concrete implementation of the JDBC API. Java EE containers take this single connection technology and provides access to them through datasources.1. A datasource is a pool of database connections that can be shared across multiple applications. Inc All Rights Reserved .3 Java Database Connectivity JDBC is a vendor independent API for connecting to SQL databases. Using a common interface means that applications can easily port from one database to another without having to re-write the source code of the application to deal with different SQL database programming interfaces. Page 16 c 2010 n + 1. JDBC is a simple connection based API fro making single connections to the database. JAVA EE OVERVIEW 1.

It allows developers to find and access remote resources seamlessly within an application. Page 17 c 2010 n + 1. JNDI can be used to gain access to a wide range of resource including both Enterprise Java beans and JDBC database connections.1. The concrete implementations of the hierarchical database are provided by each Java EE container.4 Java Naming And Directory Interface The JNDI provides an API for finding and accessing services which are organized into a hierarchical structure. Inc All Rights Reserved .Java EE Foundations 1. The important need for JNDI is that it allows developers to find resource across the network from a single location. Allowing the system administrators the flexibility to move resources across machines and change the location only within the JNDI server. Thus developers do not have to hard code resource locations within the application.

JAVA EE OVERVIEW 1. POP. SMTP. and IMAP protocols.1.CHAPTER 1. Inc All Rights Reserved . The mail services are available through the JNDI interface. Page 18 c 2010 n + 1. JavaMail supports MIME encoded email.5 JavaMail The Java EE platform includes an API for sending and receiving Internet email message from within Java applications.

Each bean provides a service to the outside world. These beans make it easy to be consumers of JMS messages.Java EE Foundations 1. Entity Beans Entity beans are wrappers for the database layers of a system. messaging.1. Message Driven Beans Message driven beans are different from the other two beans. They allow developers to provide solutions that are a asynchronous in nature. Inc All Rights Reserved . and data storage of an enterprise application. The Java EE environment provides the bean with automatic transaction management. These services can inter-operate. Page 19 c 2010 n + 1. perform transaction management. Allowing the developer to worry about the business processes and not the plumbing necessary to build large scale distributed applications. resource pooling. Each bean provides container managed persistence allowing the developers to create class based representation of data from a data store. Beans provide the heart of the business logic. The beans provide the developer with key services to assist in creating enterprise solutions. updating. state management.6 Enterprise Java Beans Enterprise Java Beans are one of the cornerstone technologies of the Java EE platform. and security. and other tasks necessary for building business processes. Session Beans Session beans are the containers for the business logic. Such a mechanism simplifies the process of adding. and deleting data from the database.

Page 20 c 2010 n + 1.7 Java IDL / RMI / RMI-IIOP Java IDL provides a utility for creating CORBA (Common Object Request Broker Architecture) objects in Java.1. This makes it simple to create distributed applications within an all Java application. JAVA EE OVERVIEW 1.CHAPTER 1. This allows Java applications to easily talk to CORBA object on the network. CORBA services include naming. RMI-IIOP extends the Java RMI communication protocol to allow RMI method calls to communicate over the IIOP protocol. Inc All Rights Reserved . and management services necessary for effectively creating distributed environments. Java Remote Method Invocation (Java RMI) provides a protocol for communicating between Java objects on different Virtual Machines. CORBA is a platform and language independent method for communicating across the network to create distributed applications. security. transaction. CORBA uses the Internet Inter-Orb Protocol (IIOP) for communicating data across the network.

Page 21 c 2010 n + 1. Inc All Rights Reserved . It is important to note that JMS guaranties the delivery of messages allowing developers to be confident about asynchronous development. JMS is a vendor neutral API.1. Like JDBC. a point-to-point and a publish-subscribe system.Java EE Foundations 1. This makes JMS messages platform independent meaning that you can easily interchange messaging systems without modifying the code using JMS. It is a messaging service for sending messages between applications across the network. The actual implementation of the messaging services is provided by the Java EE container. It supports two types of delivery mechanisms.8 Java Messaging Service JMS is an API for communication between message oriented middleware.

The headers are processed by handlers that can provide additional protocol support through third party applications (security. methods available from the service. parsing (SAX. Generally SOAP messages travel over traditional Internet protocols like HTTP. This dichotomy allows for complex messaging. XML The eXtensible Markup Language provides the foundational building blocks for web services.1. CORBA. All of these tools are license free and platform independent. Web services make previous distributed environments like Java RMI. SOAP The Simple Object Access Protocol is the protocol used for web services communications.CHAPTER 1. WSDL The Web Service Description Language is used to describe service endpoints. JAVA EE OVERVIEW 1. the parameters associated with the method and what the response message will look like. It utilizes established technologies to simplify the process of create distributed applications. XML was created as a modular language to represent structured data.9 Web Services Web services is another form of distributed computing. transactions. Web services uses XML to describe services and the interactions between these services. Tools are available to take WSDL documents and generating code stubs making it easy for developers to connect and consume web services. It includes the location of the web service. Page 22 c 2010 n + 1. There are an extensive set of tools for defining (XML Schema). SOAP messages are XML documents that are broken into a Header and Body. DOM) and transforming XML data (XSL). These older technologies were to limiting (Java RMI only available between Java VM’s and DCOM only available on Windows platforms) or to complicated (CORBA). Inc All Rights Reserved . etc). The body is consumed by the SOAP server for processing by the server application. and even Microsoft’s DCOM obsolete technologies. supported transportation protocols.

The Java EE environment makes heavy use of this information to set up the container. a classes method. Inc All Rights Reserved . Page 23 c 2010 n + 1. The meta data by definition does not effect the compiled code.Java EE Foundations 1.2 Annotations With the introduction of Java 5. The new feature is called annotations. It allows the developer to associate the meaningful data with the actual class instead of being tucked away in one of many XML configuration files. The information can be gathered by tools to perform some special function. These annotations provide a syntactical method for for assigning the custom meta data to a class. it is information that can be retrieved at runtime. The EJB3 specification uses the meta-data to define how the beans will interact with the container. If the code is not effected. a new mechanism was created that allowed developers to associate meta data with Java objects within the source code. or a classes attributes. what is the point of using annotations? While annotations do not effect the compiled code. It is just information that is attached to a class.

} Page 24 c 2010 n + 1. attributes representing the form of the meta-data is associated to the annotation. Since annotations are a data type. Java 5 accomplished this by making annotations an extension of the interface. public @interface Copyright { } After the annotation is defined. the annotation specification provides a mechanism for ordering the data into defined units. Inc All Rights Reserved . In the example below the Copyright annotation is being defined. } One of the strange aspects of annotations is the representation of attributes as methods with a return type. public @interface Copyright { String value(). package net.myannotations. The @ is used to mark the annotation data type. a value needs to be associated to the copyright.nplus1. public @interface Copyright { String value(). In this instance the attribute value is associated with the attribute Copyright and is a String.2. they must be packaged like any other type. The developer is responsible for defining the annotation and telling what type of meta-data can be associated with it.1 Creating A Customer Annotation While meta-data can represent a wide range of information. In the copyright example. In this respect the annotation is a special kind of Java type.CHAPTER 1. JAVA EE OVERVIEW 1.

or method by placing an instance of the annotation before the artifact. package net.Java EE Foundations 1. } @Copyright(value="2001") public void setData(Object data) { this.nplus1. The copyright example has one attribute value.2 Associating Annotations With A Class Using the annotation is simple.nplus1. import net.Copyright. Inc") private Object data. attribute. @Copyright(value="2009 n + 1.2. Inc All Rights Reserved . Inc") public class SimpleContainer { @Copyright(value="2008 n + 1.myannotations.data = data. @Copyright(value="2009 n + 1. Inc") private Object data. Specify the annotation and define any attributes to be associated.containers. } @Copyright(value="2001") public void setData(Object data) { Page 25 c 2010 n + 1. public Object getData() { return data. Below is an example of defining the annotation. @Copyright(value="2009 n + 1. public Object getData() { return data. } } Remember that annotations are a data type and thus they must be imported before using them within the destination class. Inc") public class SimpleContainer { @Copyright(value="2008 n + 1. Inc") The annotation can be applied to any class.

CHAPTER 1. } } Page 26 c 2010 n + 1.data = data. JAVA EE OVERVIEW this. Inc All Rights Reserved .

Annotations allow for multiple attributes to be defined.2. The same principal applies when setting the value of an annotation with an array. int [] data = {5. In this example a data array of size four is created and it is pre-populated with the values of 5. } When defining a multi-value attribute the same notation is used when creating an array through direct population. 2. date(). } public void setData(Object data) { this. } } In addition to being able to define multiple properties. Inc All Rights Reserved . Below is a modification to the last example to allow for multiple authors to be defined. Recall how arrays can be initialized by setting the values. summary(). and 1. 2. date="1/13/2009") public class SimpleContainer { private Object data. @SummaryNote(id=55. 1}. 3. String date().Java EE Foundations 1. public @interface SummaryNote { int id(). String summary(). annotations have a way to provide multiple value attributes. public Object getData() { return data. The example below defines the authors for the SummaryNote Page 27 c 2010 n + 1. 3. summary="This is a test".data = data. Each of these values would have to be defined if the annotation is associated with a particular class. String [] authors ().3 Multiple Value Annotations An annotation isn’t restricted to having one value associated with it. It is done by defining the data type as an array. Below is an example of defining multiple attributes of varying data types. public int String String } @interface SummaryNote { id().

CHAPTER 1. JAVA EE OVERVIEW @SummaryNote(id=55. Page 28 c 2010 n + 1. summary="This is a test". "Beth"} ) Notice that the author values are a comma separated list of elements inside of brackets. Inc All Rights Reserved . date="1/13/2009". authors = {"Brian".

String [] authors() default {}. @SummaryNote(summary="This is a test") The rest are the attributes are optional and can be defined if the default value is not appropriate. String date() default "Unknown". } With defaults set the only annotation attributes that must be defined are ones without a default value. Java provides such a mechanism by adding a new keyword default. In this case the summary field is the only mandatory field. Especially if some of the attributes could be set to a reasonable default that would only need to be modified occasionally.2. public @interface SummaryNote { int id() default 1. Page 29 c 2010 n + 1. String summary(). default immediately follows the attribute along with the value to be used if the attribute doesn’t exist within an annotation. Inc All Rights Reserved . Thus the annotation could be used as follows.Java EE Foundations 1.4 Default Values It would be very cumbersome to work with annotations if a developer had to fill out every value of the annotation. authors={"sarah"}) It is also worth noting at this point that a single value in an array must be contained within the curly braces. @SummaryNote(summary="This is a test".

Inc All Rights Reserved . The @Override annotation is used to ensure that a method is truly overriding a parent’s implementation. Create the following Test class import java. Add a @Deprecated annotation to the printName() method. Modify the PersonTest’s main method in Part 2 to include the annotation @SuppressWarnings(”deprecated”) What happens to the warning? Part 4. Call the printName() method to print the name to the screen. What happens when the Test class is compiled? Why does only 1 method cause the compiler to fail? Part 2. Create a second class called PersonTest and should be able to run as a Java application. Does an warning display when the application is compiled? What is the warning? Part 3. printName() should display the name on the screen. Page 30 c 2010 n + 1. It should have one attribute name and the following methods: public void setName(String n) public String getName() public void printName() Provide an implementation for each of the methods.LinkedList. Create a class called Test which contains two methods. Create a class called Person. The @SuppressWarnings annotation is used by the compiler to ignore certain warnings and not display them. In the main method create an instance of the Person class and set its name. JAVA EE OVERVIEW 1.util.3 Lab Activity Part 1. The @Deprecated annotation can be applied to a method in a class to warn the compiler that the user is trying to access a method which has been deprecated and should no longer be used.CHAPTER 1. Another use for the @SupressWarnings annotation is to handle unchecked types. public String toString() public String twoString() Mark both methods with the @Override annotation.

println(x).add("test 2"). list.out. Page 31 c 2010 n + 1. list.Java EE Foundations public class ListTest { public static void main(String [] args) { LinkedList list = new LinkedList(). for ( Object x : list ) { System. Inc All Rights Reserved .add("test 1"). } } } What happens when the class is compiled? What type of warning is issued? Add a @SupressWarnings annotation to the main method to remove the warning.

Inc All Rights Reserved . JAVA EE OVERVIEW Page 32 c 2010 n + 1.CHAPTER 1.

Chapter 2 Session Beans Objectives • Understand how session beans work • Learn how to create local and remote interfaces • Learn how to create bean implementation • Learn how to deploy session beans • Learn how to access server side session beans • Understand session bean state • Learn how to use state transition annotations 33 .

A stateful session bean is an extension of the client application. Providing a highly scalable solution. SESSION BEANS 2. or delete items from the list. stateless and stateful session bean. Their are two types of session beans available.1 What Is A Session Bean? A session bean is a special type of object that can be deployed into a Java EE environment. edit. are guaranteed to be maintained between calls to the object. Since these actions take place over time.1. it is unnecessary to maintain stateful information between calls upon the bean. Because each method is independent of one another. Why use a session bean? First off they are easy to develop in EJB3. The Java EE container is in charge of managing the instances of the bean. When developing stateless session beans any atomic method is a good candidate for inclusion within a stateless session bean. if a developer was tasked to write code to manage a todo list. A stateless session bean does not maintain state between calls on the bean. Session beans are good at organizing and executing what is necessary to perform some desired business rule. Take for example an ordering system manager. The ordering of products might be a multi-step process that interacts with a user.1. The role of the session bean is to represent the business logic or the logical flow of the application. 2.2 Stateful Session Beans Stateful session differ from stateless session beans in that they are dedicated to one client for the life of the bean. For example.CHAPTER 2. Each of these actions would be good candidates for compilation within a stateless session bean. a number of actions would be necessary to manage the list. The methods have an interdependence that forces the bean to be associated with just the single client. Page 34 c 2010 n + 1. The bean might have methods to add items. view items. Inc All Rights Reserved . The code would also need to enumerate the items in the list. The developer would need to be able to add. It behaves like any other local object and its state. The user has to select the items to order and then provide confirmation for placing the order. and the process order. attributes. The container pools the beans to maximize performance. They require few server resources because they are not dedicated to a particular client. The solution scales very well.1 Stateless Session Beans The stateless session bean is a collection of independent business methods that are related to one another. 2. What makes a session bean different from any other controller type logical mechanism is that it is managed by the Java EE container. The developer can not assume that any attributes of a stateless session bean will be maintained between calls on the bean. the bean would need to store the items being ordered between calls and before final authorization.

Page 35 c 2010 n + 1. The obvious question. Stateful beans do not scale and should be used sparingly. RMI would be overkill for the communication layer. If the system will interact with many clients. An EJB session bean is composed of three components.2 How Session Beans Work Session beans are identified with specific annotations provided for the Java EE development environment. The Java EE container creates and manages the code necessary for the client to server communication. The “remote” method uses Java RMI for handling communication across a network.1 Proxy / Stub Session beans within a Java EE environment are based upon the client / server model. The “local” method provides direct access to the bean code. The @Stateless and @Stateful annotations defined in javax. Therefore unlike stateless session beans which can share instances. The only way to communicate is through the network. The local proxy/stub is nothing more than a simple pass though to the bean. The Java RMI protocol is used to send and receive data to the bean. In this case the client virtual machine resides in a different one from the server’s virtual machine. is when would a programmer use local rather than remote? This is mostly useful in a simple Java EE environment where the Servlet/JSP resides in the same container as the deployed EJB. The proxy / stub design pattern provides the mechanism for session bean communication. Therefore they make a good candidate for a stateful session bean. Since the Servlet or JSP page runs in the same container they share the same VM.ejb package mark the bean as a session bean. 2. the EJB container. 2. The proxy is the server side component which handles incoming requests for the bean. The Java EE environment recognizes classes with the annotations and marks them for deployment as session beans. there will have to be one stateful bean for every client. and the actual instance of the EJB. EJB provides two different proxy/stub mechanisms. Inc All Rights Reserved . Among its responsibilities is routing the call to an actual bean instance within the container. The downside to stateful session beans is the fact that they have a one to one relationship with the client. The stub resides on the client and is responsible for making the request upon the proxy. The beans reside on the server and the clients access these beans indirectly through a simple remote procedure call. If the client and server reside within the same virtual machine there is no need for network based communication. They are the proxy/stubs.2. Each stateful session bean can only be accessed by one client. Stateful session beans are best used for managing complex tasks and transactions that are not atomic in nature. the system will have to manage a bean for each client. The developer does not have to worry about managing connections.Java EE Foundations In this case all of the methods are interdependent upon each other for the completion of the business case.

instantiate it and then manage it within the Java EE environment. The proxy/stub communication mechanism is always used for communication. • Instantiates and maintains life cycle for all beans • Routes invocation on proxy to actual bean implementations • Manages transactions for beans • Manages security authorization for bean calls • Pools stateless session beans for better performance and scalability All of the services provided are common elements found in any enterprise application. The bean instance is where the actual business logic code resides. Inc All Rights Reserved . it is never access directly by the client application.CHAPTER 2. The Java EE environment makes it simpler to develop applications that are enterprise solutions. It provides a number of services for managing bean instances.3 Developing a Session EJB Session beans are relatively easy to develop. Rather than letting developers create their own session pooling and transaction management services. Once the Java EE container recognizes the annotations the object’s control is taken over by the container. 2. The methods defined in the interface are the methods that will be exposed to the client Page 36 c 2010 n + 1. SESSION BEANS 2. 2. The advantage of such an arrangement is the fact that these services can be constructed and managed by the subject experts creating the Java EE container rather than some home grown solution which is likely to be inferior. The first step in the process is to create the session bean’s interface.2. The complexity is in making sure all of the right steps are done to successfully deploy the bean. It will instantiate the object as needed and pass through any life cycle messages to the instance.2 EJB Container Management The EJB container mentioned in previous sections is a construct used to represent the code which manages all EJB beans. • Creates and manages the proxy and stubs generated to handle communication.2. the container provides these services. In the EJB3 specification the bean instance is a plain old Java object (POJO) that is registered with the container through annotations. The container will take the class created by the developer.3 Bean Instance The final component is the actual instance of the bean. Since the bean instance is managed by the server.

The container will create a proxy and stub that will provide a direct link between the client and session bean instance. The following sections walk through these steps in greater detail. These compiled classes are placed into the EAR file and are made available to the Java EE container on deployment. Java’s interface mechanism is perfect for capturing these method definitions. It informs the container that the generated proxy/stub must provide inter-VM communication. It informs the container that the proxy/stub will reside within the same VM.util. Since network communication is not involved there is no need for objects passed to implement the Serializable interface. The EJB3 specification makes the implementation easy to create since it is a regular POJO. The goal is to take each atomic action and define them as a series of methods. The calculator interface will have two methods.Serializable interface. This step is logical because the generated proxy and stub code must map to an implementation of the session bean. It will use an example of a simple stateless calculator bean to explain the process. There are two types of interfaces to define. The container will create proxies and stubs that use RMI for the communication layer. Since RMI is used for communication. Once the interface is created. the next step is to create the bean code.3. Otherwise the call will throw a non serializable exception. The first action necessary to create the EAR file is to compile the source class and interfaces into byte code. The session bean can implement either or both interfaces. Inc All Rights Reserved . In addition.Java EE Foundations application. Theses methods defined by the interface will ultimately be the ones exposed to the client application. The only step left is to deploy the session bean to the server. any objects that are passed to the session bean must implement the java. Those are the only steps necessary in defining a session bean. The first will add two numbers and a second which will be tasked with subtracting two numbers. The second interface is the local interface. The first is the remote interface. The EAR file is an “enterprise archive”. The bean must implement the interface defined in the previous step.1 Remote and Local Interfaces The first step in development is to determine what actions the bean will be tasked with accomplishing. Creating The Interface A regular Java interface is used define the business methods which will be available to the client. 2. public interface Calculator { Page 37 c 2010 n + 1. Deployment to the server is accomplished through the creation and deployment of an EAR file. the developer has to specify if the interface represents the local or the remote interface.

Below shows how to mark the Calculator interface to use the remote proxy/stub mechanism.y. int y).ejb. Page 38 c 2010 n + 1. @Local public interface CalculatorLocal { public int addNumbers(int x. The example below shows an implementation of the remote Calculator interface.Remote.2 Session Bean POJO Implementation Once the interface is defined for the session bean. int y). Below is an example of a second interface marked for local access. public int subtractNumbers(int x. This is done by annotating the interface with either the javax.Local.ejb.Remote or javax. import javax. The @Remote annotation is used to mark a remote proxy/stub. int y). } 2.ejb.ejb. the developer needs to provide the implementation of the business rules. public class CalculatorBean implements Calculator { public int addNumbers(int x. } This interface can be marked either local or remote. public int subtractNumbers(int x. The @Local annotation tells the server that it will be a local proxy/stub.3. This is accomplished by creating a simple Java class that implements the interface. @Remote public interface Calculator { public int addNumbers(int x. It is possible to create a second interface and mark it local.CHAPTER 2. public int subtractNumbers(int x. } Once the interface is defined. int y). int y). int y) { return x . } public int subtractNumbers(int x.Local annotation. it is time to specify which type of interface will be used to access the bean. int y) { return x + y. SESSION BEANS public int addNumbers(int x. By applying both interfaces the client can access the bean either remotely or locally. int y). import javax. Inc All Rights Reserved .

ejb.ejb. int y) { return x + y. int y) { return x .Java EE Foundations } } The next step is to provide information to the Java EE platform to signal that the class is meant to be a session bean. the CalculatorBean needs to be marked as a stateless session bean. CalculatorLocal { public int addNumbers(int x. The javax. @Stateless public class CalculatorBean implements Calculator. } } The fact that that the CalculatorBean implements an interface that is marked @Remote tells the Java EE environment that the remote proxy/stub code needs to be made available at deployment time. int y) { return x + y. import javax.Stateless. } public int subtractNumbers(int x.ejb.y. Page 39 c 2010 n + 1. int y) { return x . If both a @Local and @Remote interface is associated with the bean implementation then the Java EE environment will make the local and remote proxy/stubs available. @Stateless public class CalculatorBean implements Calculator { public int addNumbers(int x. Inc All Rights Reserved .Stateful annotations are used to signal what type of session bean is being deployed.Stateless and javax. } } The implementation and interfaces are all that are necessary for creating a session bean within the new EJB3 specification. import javax. } public int subtractNumbers(int x.y.Stateless. In the example.ejb.

the classpath for these JAR files must be part of the build path./build"> <classpath><path refid="jboss. In JBoss. Inc All Rights Reserved . <path id="jboss./src" destdir=". In this case. The id attribute used in the path task provides an identifier that can be used when defining a CLASSPATH in the compilation section.server. This section steps the developers through the steps necessary to build an EAR file using the ANT build tool. Since the annotations from the Java EE library are used to identify session bean components. The same directory structure used by the source is created in the build directory and the . This occurs so the classes can maintain Java packaging compliance. SESSION BEANS 2.class files are placed in the same directory as the source counterparts. 2.java files are located. The target “build” above is a target used to compile the source code into class files.1 Compiling With ANT The first step in creating an EAR file is the compilation of the beans and their respective interfaces.CHAPTER 2. The javac tag invokes the javac compiler. The ANT entry below provides an example of performing this operation.4.server. The srcdir attribute determines where the . The EAR file stands for enterprise archive. the id developed in the previous path section is used to add the Java EE JAR files to the Page 40 c 2010 n + 1.4 Building EAR Deployment File EJBs are generally deployed to the Java EE server using an EAR file. but has a specific structure for enterprise deployment. It will compile all files in the src directory and any sub-directories. The classpath tag inside the javac tag specifies additional locations to look for Java libraries. the Java EE jar files used for compilation can be found in the client directory of the distribution. The include statement is used to include any JAR files within the directory structure.classpath"> <fileset dir="/opt/jboss/client"> <include name="**/*. Thus to compile the files the JAR files from this directory must be included in the CLASSPATH designation.jar"/> </fileset> </path> <target name="build"> <javac srcdir=".classpath"/></classpath> </javac> </target> The first section describes the ANT path information. It is similar to a WAR file for web applications. The destination directory is where the . The fileset defines the directory where the JAR files reside.class files will be placed after compilation.

<target name="package-ejb" depends="build"> <jar jarfile=".3 EAR File The deployment of a Java EE application is done using an EAR file. The easiest way to accomplish this task is to make sure the elements of the session bean are isolated into their own packages. In this example the ** after beans and services means it will take any files within the directory or within any subdirectory.app.nplus1.2 Packaging EJBs With ANT The next step is to take all of the artifacts from compiling the session bean and group them into an EJB centric jar file.ear extension.app.beans. It is going to be composed of files from the build directory. The interfaces go into one package. Inc All Rights Reserved . 2. The ** before means that the beans or services directory must exist somewhere under the build directory. If this isn’t done then the compiler won’t be able to find the annotations necessary for compilation.4. package net. public class CalculatorBean implements Calculator { // implementation here } With the elements in package it becomes easy to create the jar file. The EAR file contains all of the JAR files necessary to support the Java EE Page 41 c 2010 n + 1.jar"> <fileset dir=".jar will be created. It will include any files in the subdirectory of the beans or services directory./dist/acme-ejb.4./build"> <include name="**/beans/**"/> <include name="**/services/**"/> </fileset> </jar> </target> In this example the JAR file acme-ejb. package net.Java EE Foundations classpath. 2. An EAR file is a JAR file with a .services. public interface Calculator { // implementation here } The bean implementations generally go into another.nplus1.

xml The application.jar</java></module> </application> The second type of module is the ejb module.jar</ejb></module> </application> Page 42 c 2010 n + 1.xml file. and web.module info here --></module> <module><!-.xml file found in WAR files. or message driven beans and to look for the annotations necessary to deploy the them. The description provides no value to the deployment. There are three types of modules available: java. <application> <description>Simple description of the application</description> <module><java>third-party. The basic outline for the application. In addition to the JAR files.jar</java></module> <module><ejb>acme-ejb. provides important information about the Java EE application. The java module is used to specify any 3rd party JAR files that are going to be made available to the Java EE application <application> <description>Simple description of the application</description> <module><java>third-party. entity. or Message Driven beans. Entity.module info here --></module> </application> The application tag is the enclosing tag for the configuration file. The module section on the other hand. It tells the Java EE container that the contents of the JAR file are session.xml is shown below. These include the WAR file containing the web application. SESSION BEANS application. Similar to the web. Inc All Rights Reserved . and any JAR files necessary to support the WAR or EJBs. The configuration file must be placed within the META-INF directory within the JAR file.CHAPTER 2. <application> <description>Simple description of the application</description> <module><!-. A description of the application and a list of modules (JAR) files that are included within the EAR file. the EAR file must contain an application. ejb. the EJB JAR file containing any necessary Session. it provides configuration information about the Java EE application. application. The description is a tag that allows the developer to provide some information about the Java EE application.xml is a simple configuration file that contains two pieces of information. It is only useful for tools that read the EAR file.

Inc All Rights Reserved .jar</java></module> <module><ejb>acme-ejb. The web tag has two child tags: web-uri and context-root.jar</ejb></module> <module> <web> <web-uri>acme.nplus1. The path context is the path necessary to reach the web application after the root of the Java EE server is reached.net/foobie/x <context-root>/</context-root> Web App URL: http://foobie.nplus1.war</web-uri> Page 43 c 2010 n + 1.nplus1.net/acme <context-root>/foobie/x</context-root> Web App URL: http://foobie.xml file including XML header information <?xml version=’1. <application> <description>Simple description of the application</description> <module><java>third-party.war</web-uri> <context-root>/acme</context-root> </web> </module> </application> The complete application.net/ The application below includes the web module. The web-uri is the path to the WAR file containing the web application.nplus1.jar</ejb></module> <module> <web> <web-uri>acme.sun.dtd"> <application> <description>Simple description of the application</description> <module><java>third-party.com/dtd/application_1_3. the Java EE server has the domain name foobie. The context-root is used to determine the path context for the web application. The best way to understand this is to review a couple of examples. <context-root>/acme</context-root> Web App URL: http://foobie. Inc. For these example.Java EE Foundations The web module’s configuration is a bit more complicated than the other two types.jar</java></module> <module><ejb>acme-ejb.0’ encoding=’UTF-8’ ?> <!DOCTYPE application PUBLIC "-//Sun Microsystems.net.3//EN" "http://java.//DTD J2EE Application 1.

ANT can be used to build the EAR file. It has two attributes.server./conf/build. The appxml attribute tells where ANT can find the application.properties"/> <path id="jboss.package-ejb"> <ear destfile="${dist}/acme. SESSION BEANS <context-root>/acme</context-root> </web> </module> </application> Creating EAR File With ANT Once the application.classpath"> <fileset dir="${jboss. The ear tag is used to construct the file.jar"/> </fileset> </ear> </target> Below is a complete example of a build.copy war file to deploy directory</echo> <echo>clean . Inc All Rights Reserved . <project name="My Project" default="build-targets" basedir=".package web app into war file</echo> <echo>deploy .CHAPTER 2.lib}"> <include name="**/*.xml"> <fileset dir="${dist}"> <include name="acme-ejb.xml file that includes everything necessary to compile EJBs and the WAR file. The destfile attribute is used to determine where the assembled EAR file will be placed. <target name="package" depends="package-web.jar"/> <include name="acme.xml file.war"/> <include name="third-party."> <property file=".cleans build and dist directories</echo> </target> <target name="build"> Page 44 c 2010 n + 1.jar"/> </fileset> </path> <target name="build-targets"> <echo>My Build System Targets</echo> <echo>build .acme}/application.xml file is configured for the Java EE application.builds servlets and custom classes</echo> <echo>package .ear" appxml="${conf. The fileset tag can be used within the ear tag to list the JAR files necessary for the application.

/dist/acme./dist/acme.server./src/" destdir="./build"/> <delete dir="./jsp"/> </war> </target> <target name="deploy" depends="package-ear"> <copy file=".war" webxml=".jar"> <fileset dir=". Page 45 c 2010 n + 1./dist/acme-ejb. Access to the beans is controlled by the Java Naming and Directory Interface or JNDI server for short./build"> <include name="**/beans/**"/> <include name="**/services/**"/> </fileset> </jar> </target> <target name="package-web" depends="package-ejb"> <mkdir dir="./build"> <include name="**/web/**"/> </classes> <zipfileset dir=".5 Accessing Session Bean Once the session beans are deployed to the server.xml"> <classes dir="./build/"/> <javac srcdir=". The user must query the JNDI server to gain a reference to the services remote/ local stub. Once the client has access to stub. Inc All Rights Reserved ./conf/web.ear" todir="${jboss.Java EE Foundations <mkdir dir="./dist"/> <war destfile=". calls can be made to the service as if it were a local method.classpath"/> </classpath> </javac> </target> <target name="package-ejb" depends="build"> <jar jarfile=".deploy}"/> </target> <target name="clean"> <delete dir=". The stub handles all of the communication necessary to talk with the session bean on the server./build"> <classpath> <path refid="jboss./dist"/> </target> </project> 2. they are accessible for use to outside applications.

jnp.naming package provides the entry point for accessing the JNDI API. The developer can use JNDI to gain access to either the local or remote stub depending on the look up value.CHAPTER 2.interfaces"). Each resource is associated with a name. the InitialContext can only be instantiated and invoked using a process that is unique for each Java EE container.factory. props. javax.jnp.naming. Since the stub implements its respective interface the object can be cast to that interface. In the case of session beans a reference to the stub the is returned to the end user.util. All the developer needs to know is the name and they can retrieve the resource from the JNDI server.factory.url value tells the context where to connect when making JNDI requests.factory.InitialContext initialContext = new javax. JNDI uses a hierarchical structure to organize resources similar to a file system.naming.util to provide information about self instantiation and connecting to the JNDI server. java.naming.setProperty("java.url.interfaces. An example of a JNDI look up is shown below.naming. The ’/’ character. In fact each layer of the hierarchy uses the same separator used by Unix/Linux file systems.NamingContextFactory").provider. Initial Context The InitialContext interface defined in the javax.Properties props = new java. The API is platform independent whose concrete implementation is accessed through an initial context. "jnp://localhost:1099").naming.setProperty("java.pkgs". Inc All Rights Reserved .jboss.5. SESSION BEANS 2. Below is an example of creating a the InitialContext using the JBoss Java EE container. acme/CalculatorBean/remote acme/TransactionBean/local The JNDI server returns a reference to the resource associated with name.url".initial".naming:org. All subsequent calls to the object will make the necessary calls to communicate with the bean residing on the server. Page 46 c 2010 n + 1.naming.initial option tells the InitialContext what factory to use when instantiating an instance of itself. In this instance the local machine is the JNDI server and listens to port 1099.setProperty("java.util. Like JDBC. Each Java EE container is required to provide an implementation of the JNDI API.provider.InitialContext(props). "org. "org.naming. props. The java. The java. props.1 JNDI The Java Naming and Directory Interface provides a simple mechanism for accessing container managed resources. JBoss uses the Properties object in java.Properties().

a Calculator bean was created.ear file. The protocol used for transportation in CORBA is IIOP or Internet Inter Object Protocol. it can be used to access the EJB’s deployed to the server. JBoss uses a simple mechanism based upon the EJB’s implemented name.lookup("acme/CalculatorBean/remote"). The communication between the client and the session bean is set up to use Java RMI. Thus the two JNDI look ups for the remote and local interfaces are shown below. It was created and deployed within the acme. The method returns the converted object as type Object. The narrow method takes two arguments. Page 47 c 2010 n + 1. Allowing Java objects to plug seamlessly into a CORBA architecture.PortableRemoteObject provides a narrow method which performs the conversion. It is actually CORBA. But the underlying communication protocol is not Java RMI. Object ref = initialContext. The example below assumes the developer wants to return the remote interface. The naming conventions for finding an EJB within is JNDI name store is different for each Java EE container. 2. It is meant to be a platform and language independent mechanism for communication between software programs. Since IIOP is language independent.2 Accessing Bean Once an InitialContext is constructed. it doesn’t support the concept of casting. The first step in the process is to determine the JNDI name for the EJB a developer wishes to access. CORBA stands for The Common Object Request Broker Architecture. the EAR file it belongs to and the type (remote or local) of EJB being accessed.rmi. The task is accomplished by performing a look up on the JNDI store. acme/CalculatorBean/remote acme/CalculatorBean/local The second step is to retrieve the object from the JNDI store. At this point a bit of an explanation about the communication protocols are necessary. Java created a RMI/IIOP to allow Java developers to use RMI for the interface and IIOP for the protocol.5. The javax.Java EE Foundations This information is used by the InitialContext to instantiate an instance of the NamingContext concrete class implemented by JBoss developers. It had both a remote and local interface. Thus the result needs to be cast to the proper type. it is a simple process of gaining access to the EJB. [EAR Name]/[Bean Name]/[remote | local] In previous sections. The object to convert and the destination class. Inc All Rights Reserved . Thus a special method is necessary to do the object conversion. Once the context is instantiated. The implementation was CalculatorBean.

initial". Calculator. "org.PortableRemoteObject.services.Properties.naming.class).InitialContext. 54). props. System. Object ref = initialContext.rmi.lookup("acme/CalculatorBean/remote").setProperty("java. Calculator.lookup("acme/CalculatorBean/remote"). The object can now be accessed as any other local object. } } The process for using a local interface is similar. Calculator calc = (Calculator) PortableRemoteObject.naming:org.rmi.setProperty("java.lookup("acme/CalculatorBean/local").println("215 + 54 = " + results). SESSION BEANS Object ref = initialContext.PortableRemoteObject net.out.naming.nplus1.class). Calculator calc = (Calculator) javax. The only difference is that the narrow() method is unnecessary. Object ref = initialContext. "org.naming.jboss. System. Since the session bean resides in the same VM as the client application RMI/IIOP communication is unnecessary and not used. Thus it is possible to directly cast the object to the desired type. import import import import java.url". javax.out. props. In this instance.narrow(ref.narrow(ref. Calculator calc = (Calculator) PortableRemoteObject. 54).setProperty("java.addNumbers(215.Calculator.naming.class). int results = calc. javax.interfaces.NamingContextFactory").lookup("acme/CalculatorBean/remote"). Below is the complete client application. Object ref = initialContext. public class CalculatorApp { public static void main(String [] args) { Properties props = new Properties().CHAPTER 2.factory. Page 48 c 2010 n + 1.addNumbers(215.jnp.jnp.url. int results = calc.narrow(ref.app. props.pkgs". InitialContext initialContext = InitialContext(props). the bean is being cast to the remote interface.provider.interfaces").util. Calculator. "jnp://localhost:1099").factory.println("215 + 54 = " + results). Inc All Rights Reserved . All of the communication to the server is handled by the bean.

etc The @PreDestroy annotation is associated with a method which will be invoked before the bean is destroyed by the Java EE container. Once the Java EE container no longer needs the bean it destroys the object.out. In this example the local interface is used in the JNDI look up. int results = calc. it is important to understand the life cycle of the two different types of session beans. System.open(). @PostConstruct public void init() { conn = new MyConnection(). software system. 2. The Java EE specification provides annotation for each life cycle state change. Below is an example of how these annotations might be used. } @PreDestroy Page 49 c 2010 n + 1. 2. A method with the annotation @PostConstruct is invoked right after the bean is created by the Java EE container. private MyConnection conn. It has two states: does not exist and methodready. Since the bean is stateless. The bean’s state transitions from the method-ready pool to the does not exist state in the process.6.1 Stateless Session Bean Life Cycle The stateless session bean has the simplest life cycle. The method must not have any arguments and can be used to initialize the state of the stateless session bean.Java EE Foundations Calculator calc = (Calculator) ref. A good candidate for the @PostConstruct for a stateless bean would be a connection to another system resource such as a database. and the method will be invoked when each life cycle event occurs.println("215 + 54 = " + results). Each of these transitions are marked by the container and alerts are available to the developer through the use of annotations. 54). It is an ideal location to close any connections that are created in the @PostConstruct method. any state information should be autonomous. When the session bean is instantiated it transitions from not existing to a method-ready pool for use by external client applications. The developer attaches the annotation to a method. Inc All Rights Reserved .6 Life Cycle Of Session Beans While the developer doesn’t control the creation of session beans or how they are managed. conn. Remember that consecutive calls to the same bean is not guaranteed and is unlikely.addNumbers(215.

CHAPTER 2. SESSION BEANS public void destroy() { conn.close(); }

2.6.2 Stateful Session Bean Life Cycle
The stateful session bean’s life cycle is considerably more complicated than the stateless session bean. It has the same states as a stateless bean, does not exist and method-ready, plan an additional passive state. When a stateful session bean is instantiated by the container, it transitions from the does not exist state to method-ready and is associated with a single client application. Once the client dissociates with the bean, the Java EE container will destroy the object moving it into the does not exist state. In addition the stateful session bean can timeout if not used in a certain period specified by the container. A timeout will also force the object into a does not exist state. The problem with stateful session beans are they are matched one to one with a client. Therefore each client will have its own unique instance of the stateful session bean associated with it. If a lot of clients use the service then a large number of stateful beans can be created. If the life span of those connections are relatively short, the scenario isn’t a problem for the Java EE container. The bigger problem is if there are a lot of client connections and they hold onto those connections for an extended period of time and only call them occasionally. Such an instance would drain the Java EE container of necessary system resources such as memory. The Java EE specification provides a mechanism for conserving resources by passivating stateful session beans during a period of inactivity. Passivization is the process of storing the stateful bean outside of physical memory. While the specification doesn’t tell the container how to passivate, it is generally accomplished through serialization, but not always. The container provides two signals allowing the developer to handle transient data during the passivization process. The @PrePassivate annotation marks a method which will be called before passivization takes place. Here the developer can clean up any transient data. A good example is a reference to an external log file. The connection can be closed before passivization. The @PostActivate annotation marks a method which is called once the stateful bean leaves passivization and before it enters the method-ready state. Here the transient state can be reset. In the log file example, the log file can be re-opened. The stateful session bean can also move from the passive to the does not exist state if the bean times out while passivated. If a bean is passivated when a timeout occurs, the the @PostActive method never fires. Instead the @PreDestroy annotation will be called. An additional annotation is available to the developer to signal that the stateful session bean is no longer needed. The @Remove annotation provides this functionality. When a method marked with the @Remove annotation is invoked the Java EE container will remove the bean firing the @PreDestroy signal and moving the bean into the does not exist state. @Stateful Page 50 c 2010 n + 1, Inc All Rights Reserved

Java EE Foundations public class MyBean implements LocalInterface { private ArrayList&lt;Person&gt; people; private FileWriter out; @PostConstruct public void initialize() { people = new ArrayList&lt;Person&gt;(); out = new FileWriter("/tmp/foobie.log"); } @PreDestroy public void destroy() { if ( out != null ) { out.close(); } } @PrePassivate public void startPassivation() { out.close(); out = null; } @PostActivate public void endPassivation() { out = new FileWriter("/tmp/foobie.log", true); } @Remove public void shutdown() { // signal to remove stateful bean } }

In this example the stateful session bean has an ArrayList it used to keep track of People objects. In addition it has access to a FileWriter to use for logging. When the client application asks for an instance of MyBean, the bean is constructed and the @PostConstruct method initialize() is called to run by the container. Because the FileWriter is a transient variable, the session bean closes the file connection before passivization and re-instates it once passivization ends. Since the bean can be in a passivated state when it is destroyed the @PreDestroy method must make sure that the FileWriter exists before attempting to close the connection. The method annotated with @Remove can be called to alert the container to remove the bean invoking the @PreDestroy method. Page 51 c 2010 n + 1, Inc All Rights Reserved

CHAPTER 2. SESSION BEANS

2.7 Lab Activity
Part 1.

Page 52

c 2010 n + 1, Inc All Rights Reserved

Chapter 3

Entity Beans
Objectives
• Understand what an entity bean is • Understand what an EntityManager is • Learn how to create entity beans • Learn how entity beans interact with the EntityManager • Understand how to create a persistence unit • Learn how to add entity beans to deployed EJB Jar file

53

the Session Bean.CHAPTER 3. The goal is to model the data of objects and the object relationships within in a flat relational table space. ENTITY BEANS 3. Inc All Rights Reserved . The Session Bean and Entity Beans are used in tandem to provide an implementation of business rules. the Entity Bean. This module will walk the developer through the mapping process and then consider how to use these entity beans to retrieve and store data within a relational database.1 What is an Entity Bean? The Java EE standard provides for three types of Enterprise Java Beans. The Entity Bean is used to represent the data of an application. OR mapping is the process of mapping data between an Object Oriented framework and a relational database. The Session Bean represent the business logic of an application. Page 54 c 2010 n + 1. The method of mapping objects to data stores is known as Object Relational (OR) mapping. The Message Driven Bean is used to handle asynchronous messaging. and the Message Driven Bean. In most cases the data store is a database. The Entity Bean defines a relationship between the bean and the data store.

A project that used a large number of entity beans would mean a configuration XML file that could be hundreds of kilobytes in size. but it moved all of the logic inside the source code for each bean. In this instance the developer was tasked with providing the logic for persisting the bean’s data to the data store. If the developer wants to use Java Persistence API in any Java application. The XML documents used for the mapping were incredibly complex and unwieldy.1 Managed Persistence Java EE from the beginning was meant to be a system for providing enterprise class functionality to the developer. This development structure makes it much easier to manage a large number of entity beans because the mapping logic resides within each individual class. and delete the data from the store.0 API. Inc All Rights Reserved . object pooling. Since much of the persistence logic was duplicate code. The Java EE container continued to provide transaction management.1. The focus of this module will be to look at how to use persistence within the Java EE framework. This included all of the SQL necessary to insert. The method of persistence was defined in the Java Persistence 1. This proved to be a very cumbersome and time consuming process. and security for accessing the bean. A lot of duplication of coding logic was necessary between entity beans. object pooling. it can be used as a stand alone framework. Not something that could be easily managed. One of the goals was to provide developers with a mechanism for managing persistence of business data. The third version of the entity bean introduced entity managed persistence. The complexity and difficulty in using the entity bean meant few implemented the solution. it still was overly complicated. Another benefit to the third version of persistence was the ability to detach it from the Java EE container. and security. All the developer was left to do was map the entity bean to database. The initial version of entity bean used bean managed persistence. From this concept. The second version of the entity bean introduced container managed persistence. It took advantage of annotations introduced in Java 5 to be able to map each object to the database within the source code. The Java EE environment provided transaction management. While this was a huge improvement on the first version. the container managed the persistence logic for the entity bean. Page 55 c 2010 n + 1.Java EE Foundations 3. update. the entity bean was developed. Not only did it simplify the complexity from version 2.

ENTITY BEANS 3. Its role is to manage the collection of entities. The first is the entity bean.CHAPTER 3.2 Entity Managed Persistence Entity managed persistence is composed of four separate components. The entity bean represents the data to be stored in the data store. It is charged with selecting data from the database or updating the database with any changed values. Inc All Rights Reserved . It is charged with filling out the entity beans data and inserting. The third component is the persistence context. The second component is the entity manager. updating. and removing data from the data store based upon the contents of the bean. The fourth component is the database itself.1. Page 56 c 2010 n + 1.

The role of the developer in creating an entity bean is to provide the annotations necessary to map the entity shown above to a table or series of tables within the database. Inc All Rights Reserved . Person Table ----------------------------------| id | first name | last name | ----------------------------------| 100 | John | Doe | | 101 | Jane | Doe | | 102 | Beth | Smith | ----------------------------------The developer would create an object that has the same characteristics of the table. This will be covered in greater detail later. public public public public public public } Each row of the person table would represent an instance of the entity. Annotations are used to map the entity bean to the database table. Entity Beans are plain old Java objects. private String firstName. void setId(int id) { this. } void setFirstName(String name) { this.Java EE Foundations Entity Beans Like their cousins the Session Bean. public class Person { private int id.id = id.lastName = name. Take the following database table. } String getFirstName() { return firstName. } int getId() { return id. The entity manager would be in charge of creating the Person object an filling it with data from the table. Each instance of an entity bean represents a row in the database table.firstName = name. } void setLastName(String name) { this. } String getLastName() { return lastName. private String lastName. } Page 57 c 2010 n + 1.

When an entity bean is in a managed state. In this un-managed state. it becomes detached from the manager. There is one aspect of the new persistence management that differentiates it from bean and container managed persistence in earlier versions of Entity Beans. Each bean had logic embedded that made it dependent upon the data source. It becomes just another normal Java object. ENTITY BEANS Entity Manager The Entity Manager defined in the Persistence API provides two roles for the developer. Inc All Rights Reserved . it doesn’t have the same direct connection to the data store. Because the new persistence layer use POJOs. That difference resides with how the beans are connected to the data source. When the entity bean leaves the scope of the entity manager. It manages the mapping of an entity to a database table. Thus the entity beans are not restrained to the Java EE container. The second role is to manage the persistence context. The entity manager will insert or delete managed entities as requested by the developer. the manager updates the database with the changes. It is charged with filling in entity bean’s data from the database and is tasked with updating data in the database if values within the entity bean are modified. Whenever the entity changes state. It is charged with making a connection to the database and providing dialect specific information used by the persistence context to manage the connection with the database. For this to work each entity bean must be tracked by the entity manager and are grouped into one of two states. the entity bean is no longer tracked by the entity manager. Page 58 c 2010 n + 1.CHAPTER 3. With bean and container managed persistence each entity bean was directly tied to the database. the entity is tracked by the entity manager. managed and un-managed. It is considered attached to the manager.

Table 3. Page 59 c 2010 n + 1.2 Creating An Entity Bean As stated in the previous section. Annotation @Entity @Table @Id @Column Description Marks the class as an entity bean so it can be mapped Maps the class to a table in the database Maps an attribute to a primary field in the database table Maps an attribute to a column within the database table Table 3. an entity bean is a plain old Java object that has annotations which map the object’s attributes to tables in the database.1: Common EntityManager Methods The next sections step the developer through the process of using these annotations to create an entity bean and map it to a table in the database. Inc All Rights Reserved .Java EE Foundations 3.1 provides a list of annotations used in marking up an entity bean.

private String lastName. private String department. Inc All Rights Reserved . and department name.2. A sample of what the data might look like is shown in the table below. } public void setFirstName(String name) { firstName = name. last name. private String firstName. create table employee ( employee_id integer primary key. ENTITY BEANS 3. } public void setLastName(String name) { lastName = name. last_name varchar(50). --------------------------------------------------------------| employee_id | first name | last name | department | --------------------------------------------------------------| 100 | John | Doe | Accounting | | 101 | Jane | Doe | Information Technology | | 102 | Beth | Smith | Information Technology | --------------------------------------------------------------- The first step in the process is to create a POJO with attributes matching the fields from the database table outlined above. it is important to have the schema of the database table which is being modeled by the entity bean. The Employee class would need attributes for the employee id. department varchar(50) ). first_name varchar(50). In the sections that follow. public class Employee { private int employeeId.1 Mapping to Database Table To be able to walk through the steps to creating an entity bean. the schema outlined below will be used.CHAPTER 3. } Page 60 c 2010 n + 1. public void setEmployeeId(int id) { employeeId = id. first name.

} public String getDepartment() { return department. } public String getFirstName() { return firstName. } public int getEmployeeId() { return employeeId.Java EE Foundations public void setDepartment(String department) { this. } public String getLastName() { return lastName. } } Page 61 c 2010 n + 1. Inc All Rights Reserved .department = department.

private String lastName. Page 62 c 2010 n + 1. @Entity @Table(name="employee") public class Employee { private int employeeId. @Column(name="first_name") private String firstName. private String lastName. private String firstName. /* getter and setter methods go here */ } The next step is to use the @Table annotation to map the entity to a table in the database. This is accomplished by associating the @Entity annotation with the Employee class1 . @Column(name="last_name") private String lastName. the @Column annotation is used to map attributes to the respective column in the database. Each attribute needs to be mapped to a column in the database table. They will be replaced with a comment noting where they belong within the code. private String department. @Entity public class Employee { private int employeeId.CHAPTER 3. @Entity @Table(name="employee") public class Employee { @Column(name="employee_id") private int employeeId. ENTITY BEANS Converting POJO To An Entity Bean The first step is to mark the class as an entity bean. 1 The examples in this section will leave out the getter and setter methods to allow for brevity. /* getter and setter methods go here */ } Once the table is named. Inc All Rights Reserved . private String firstName. The name attribute for the Table annotation is used to provide the name of the table to map. private String department.

The @Column annotation is only necessary for attributes that don’t map directly to the table column names. @Column(name="first_name") private String firstName. /* getter and setter methods go here */ } Notice that the department attribute did not garner a @Column annotation. Inc All Rights Reserved . private String department. In the case of the Employee class the employee id is the primary key. In this instance the department attribute matches the name of the department column in the employee table. As one can see. The entity bean will try to map the name of the attribute to the database column. @Column(name="last_name") private String lastName. Thus a @Column annotation is unnecessary. It turns out that the @Column annotation isn’t mandatory. The attribute which contains the primary key needs to be marked by the @Id annotation. There is one more step in the process. Page 63 c 2010 n + 1. /* getter and setter methods go here */ } That is all that needs to be done! The Employee entity bean has been defined and is ready to use with an EntityManager. it is a very simple and quick process to create entity beans and use them within the Java EE environment.Java EE Foundations private String department. @Entity @Table(name="employee") public class Employee { @Id @Column(name="employee_id") private int employeeId.

@Entity @Table(name="employee") public class Employee { @Id @GeneratedValue(strategy=GenerationType.CHAPTER 3. The most commonly used are AUTO and SEQUENCE. The Persistence API provides an annotation that will allow entity beans to use these auto generators to define the beans primary key attribute. The @GeneratedValue annotation is used to determine what type of generated value is created. The @SequenceGenerator annotation provides this functionality.AUTO) @Column(name="employee_id") private int employeeId. private String department. The second attribute. The first. Inc All Rights Reserved . assigns a local name to the sequence. is used to provide the name of the sequence defined in the database. ENTITY BEANS Generated Database Keys Most of the time. The persistence is done by using the EntityManager’s persist() method. When using a sequence to define the primary key. @Column(name="first_name") private String firstName. Below is an example of using the @SequenceGenerator assuming the sequence “employee sequence” exists in the database. Below is an example of defining an auto generator. When defining the strategy attribute for the @GeneratedValue annotation the appropriate GenerationType enum must be selected. the database table will be configured to automatically generate primary key values in a table. Page 64 c 2010 n + 1. name. /* getter and setter methods go here */ When an entity bean’s values are persisted to the database the entity’s values are inserted into the table. a mechanism is necessary to map the database sequence to the generator. The EntityManager and its methods will be covered in greater detail later. The @SequenceGenerator has two attributes. But when the entity bean is persisted to the database using the EntityManager’s persist() method along with a @GeneratedValue annotation the primary key field is automatically generated and both the database and entity reflect that new value. sequenceName. @Column(name="last_name") private String lastName. There are a couple of different strategies for auto generated fields. Once the @SequenceGenerator is defined it can be tied back to the @GeneratedValue annotation by associating the local name with the generator attribute.

it has effectively linked the generator to the defined sequence. /* getter and setter methods go here */ The employee sequence is associated with the local name employee-seq using a @SequenceGenerator annotation. Inc All Rights Reserved . generator="employee-seq") @Column(name="employee_id") private int employeeId. name="employee-seq") public class Employee { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE.Java EE Foundations @Entity @Table(name="employee") @SequenceGenerator(sequenceName="employee_sequence". @Column(name="last_name") private String lastName. Once the local name is connected to the @GeneratedValue annotation’s generator. @Column(name="first_name") private String firstName. When the entity bean is persisted to the database using the EntityManager’s persist() method the sequence “employee sequence” is used to generate a new value to be used to fill out the employee id. Both the database and entity bean are given the sequence generated value. private String department. Page 65 c 2010 n + 1.

util. It would be much simpler if the generic java. ENTITY BEANS Temporal JDBC provides three types for managing date and time information.sql. @Entity @Table(name="employee") @SequenceGenerator(sequenceName="employee_sequence". @Column(name="first_name") private String firstName.Timestamp Table 3.util.Date class.Time. Temporal Type TemporarlType. Page 66 c 2010 n + 1.Date java.sql. The @Temporal annotation provides such functionality.Time java.2: Temporal Types Applying the temporal to the entity bean is a simple process shown in the example below. The java.3 shows the different temporal types and what Java data type they map to. All the developer has to do is associate a temporal type with an attribute and the EntityManager will make the conversions.CHAPTER 3.sql. generator="employee-seq") @Column(name="employee_id") private int employeeId.util.TIME TemporarlType. name="employee-seq") public class Employee { @Id @GeneratedValue(strategy=GenerationType.Date object for storing and working with times and dates. Timestamp t = new Timestamp(date.sql data types and the java.sql time data types is the constant need for conversion. javax.getTime()).SEQUENCE. @Column(name="last_name") private String lastName. the developer is forced to convert between javax. Table 5.sql. Date d = new Date(t. Inc All Rights Reserved . private String department. The problem with using these javax.util. javax.Date object could be used and force the EntityManager deal with the the conversion between data types. These represent the three different date types supported by most databases.Timestamp class.Date. Therefore.Calendar class uses the java. and javax.getTime()).DATE TemporarlType.TIMESTAMP Java Data Type java.sql.sql.

util.Date data type.DATE) private java.Java EE Foundations @Column(name="start_date") @Temporal(TemporalType.util. Page 67 c 2010 n + 1.Date startDate.sql. The @Temporal annotation maps that java. /* getter and setter methods go here */ In this instance the startDate attribute has a java.Date when inserting and updating the entity within the database.util. Inc All Rights Reserved .Date object to the database data type java.

@Column(name="first_name") private String firstName. Page 68 c 2010 n + 1. ENTITY BEANS Transient What if the entity bean needs an attribute that is not stored within the database? This can happen. Inc All Rights Reserved . generator="employee-seq") @Column(name="employee_id") private int employeeId. The Persistence API provides a @Transient annotation which tell the entity manager to ignore the object’s attribute and value.Date startDate. /* getter and setter methods go here */ In this example.DATE) private java. private String department. name="employee-seq") public class Employee { @Id @GeneratedValue(strategy=GeneratedValue. the attribute numberVacationDaysLeft is a value that is only available to the object and is not stored in the database. The attribute is passed over by the EntityManager. By default all attributes are explicitly or implicitly mapped to a table column. @Column(name="start_date") @Temporal(TemporalType.CHAPTER 3. Normally it occurs when a developer needs an attribute which holds a value that can be calculated dynamically from other pieces of data within the entity bean.SEQUENCE. @Transient private int numberVacationDaysLeft. @Column(name="last_name") private String lastName.util. @Entity @Table(name="employee") @SequenceGenerator(sequenceName="employee_sequence".

3 Using An Entity Manager The EntityManager is the key element of the persistence layer.Java EE Foundations 3. It handles all of the work necessary to manage the entity beans and persist them into the database. Inc All Rights Reserved . This section takes a look at how to instantiate an EntityManager and use it to manage Entity Beans. Page 69 c 2010 n + 1.

. The first step is to define the entity manager as an attribute of the session bean.3.. } The unitName attribute of the PersistenceContext annotation is used to map the context to a data source. .1 Obtaining The Entity Manager The entity manager within the Java EE environment is normally used within the context of a session bean. There is no need to directly instantiate the EntityManager object.. @Stateless public class MyBean implements MyRemoteInterface { private EntityManager manager. Once the annotation is defined. @Stateless public class MyBean implements MyRemoteInterface { @PersistenceContext(unitName="foobieDS") private EntityManager manager. the Java EE container instantiates the manager attribute when the session bean is created. ENTITY BEANS 3.CHAPTER 3. How this is defined will be discussed later. . Inc All Rights Reserved .. Therefore the need to initialize and configure the EntityManager is simplified. } The next step is instantiating the EntityManager and associating it with a persistence context. Page 70 c 2010 n + 1. Both of these steps are accomplished by adding a @PersistenceContext annotation to the attribute...

Method persist(Object entity) remove(Object entity) find(Class class. } That is all that is necessary to add a new entry to the person table! The EntityManager takes the annotation marked POJO marked and performs all of the work to insert the data into the database. Table 3. person. Description inserts entity into database removes entity from database retrieves entity from database based on primary key value returns Query that can be used to return Page 71 c 2010 n + 1. String first.setId(id).setFirstName(first). If a developer wants to persist an entity bean the user would pass the entity bean to the persist method and the database will be updated to reflect the new entry. person.persist(person). public void addPerson(int id. String last) { Person person = new Person(). person.3.3 provides a list of methods available to the EntityManager. Below is an example of adding a new person to the database. manager.Java EE Foundations 3. Object key) createQuery(String query) multiple entities refresh(Object entity) flush() resets the entity with data from database provides forced synchronization with managed beans and database Table 3. Inc All Rights Reserved .3: Common EntityManager Methods The methods are fairly simple to use.2 Entity Manager Methods Once the entity manager is created.setLastName(last). it has a set of methods for working with entity beans.

The entity is looked up by the primary key and any changes within the attributes are updated in the database. Inc All Rights Reserved .3.find(Person. ENTITY BEANS 3. Besides updating the data source the detached bean will also become attached in the process.merge(person). When the method finishes the “transaction” ends and the person’s last name is updated within the database. The integer value in this case is auto-boxed and transformed into an Integer object. public void updatePersons(Person person) { manager. What about detached entities? How can they be updated in the database. String last) { Person person = manager. id).setLastName(last). The EntityManager has a merge(Object entity) method which can be used to synchronize the detached entity with the database. The EntityManager’s merge method is called.3 Updating Data One might have noticed that none of the methods for the EntityManager from the previous section dealt with updating the database with any changed contents of the entity bean. person.CHAPTER 3. } In the example above the find() method is used to retrieve the entity from the database. These updates occur at the end of a transaction or the flush() method of the entity manager is called. The Person object returned is used to set a new last name. public void updatePersonsLastName(int id. Page 72 c 2010 n + 1. That is because all entity beans which are in a managed state are automatically updated in the database when changes are made. It uses the id field which would be the primary key for the person to retrieve the entry.class. } In the example shown above the Person object is assumed to be detached.

Page 73 c 2010 n + 1. It is time to bring it all together and create a session bean that uses the EntityManager and Employee bean to manage the employee table within the database.4 Example Session Bean to Manage Employee Entity The module up to this point has shown how to create an entity bean and how the entity bean interacts with the entity manager.Java EE Foundations 3. Inc All Rights Reserved .

Id. javax. the entity beans will be traveling across the network to the remote client. Inc All Rights Reserved . Objects crossing the network must implement the java. javax. @Column(name="first_name") private String firstName. import import import import import import import import java. generator="employee-seq") @Column(name="employee_id") private int employeeId. name="employee-seq") public class Employee implements Serializable { @Id @GeneratedValue(strategy=GenerationType.Entity.Serializable interface. } public void setLastName(String name) { lastName = name.Serializable. ENTITY BEANS 3. } public void setFirstName(String name) { firstName = name.GenerationType.util.persistence. javax.Column.persistence. } public void setDepartment(String department) { Page 74 c 2010 n + 1. @Column(name="last_name") private String lastName. private String department. /* getter and setter methods go here */ public void setEmployeeId(int id) { employeeId = id.SEQUENCE.4.persistence. javax. javax. javax.SequenceGenerator.GeneratedValue.util.persistence.1 Employee Entity Bean Below is the Employee entity bean used for this exercise.persistence.persistence. Since a remote interface is being used.CHAPTER 3.persistence. @Entity @Table(name="employee") @SequenceGenerator(sequenceName="employee_sequence".Table. javax.

department = department. } public String getFirstName() { return firstName. } public String getLastName() { return lastName. } public int getEmployeeId() { return employeeId. } Page 75 c 2010 n + 1. } public String getDepartment() { return department. Inc All Rights Reserved .Java EE Foundations this.

ENTITY BEANS 3.EntityManager.CHAPTER 3.PersistenceContext. In addition to basic object management. and delete employees from the database. Inc All Rights Reserved . it must be able to retrieve employees from the database.2 Employee Manager Session Bean The session bean must be able to add. interface RemoteEmployeeManager { public void addEmployee(Employee employee).4. The RemoteEmployeeManager provides the remote interface definition for the session bean. } From the remote interface.Stateless.persistence. the stateless session bean can be created. import javax. import javax. public List<Employee> listEmployees(). public class EmployeeManagerBean implements RemoteEmployeeManager { @PersistenceContext(unitName="foobieDS") private EntityManager manager. public void removeEmployee(int employeeId). public void updateEmployee(Employee e). public void addEmployee(Employee employee) { // add employee code } public Employee getEmployee(int employeeId) { // get employee code } public void removeEmployee(int employeeId) { // remove employee code } public void updateEmployee(Employee e) { // update employee code } public List<Employee> listEmployees() { // list employees code } } Page 76 c 2010 n + 1. import javax.persistence. edit. public Employee getEmployee(int employeeId).ejb.

Java EE Foundations 3.4. perform the auto generation of the key and insert the data from the attributes into the database. } The persist() method will take the employee. Page 77 c 2010 n + 1. public void addEmployee(Employee employee) { manager. Inc All Rights Reserved .persist(employee).3 Adding New Employee Adding a new employee to the database is a simple process. Use the EntityManager’s persist method to add the employee.

public Employee getEmployee(int employeeId) { Employee employee = manager. ENTITY BEANS 3.CHAPTER 3. The results from the query are used to populate the Employee bean. department FROM employee WHERE employee_id = ? The question mark represents the employeeId passed into the method. employeeId). It tells the EntityManager which class to instantiate and fill with data from the database. It uses the @Columns defined in the bean to generate a SQL call similar to the following. The second argument tells what value to look up for the @Id field of the defined class.class. } The find() method takes two arguments.4. In this instance the Employee class is loaded. first_name.4 Finding Employees Before a discussion of removing an Employee can be made. last_name. a look at finding employees must first be discussed. The first is the class which is going to be returned by the find() method. The EntityManager takes the value in employeeId variable and performs a look up on the Employee’s @Id field.find(Employee. Page 78 c 2010 n + 1. This method can be used to retrieve the Employee object for the getEmployee() method on the session bean. return employee. SELECT employee_id. The EntityManager has a find() method which is used to look up an employee from the database based upon a primary key. Inc All Rights Reserved .

Notice that the bean must be a managed bean to be subject to removal. Page 79 c 2010 n + 1. Inc All Rights Reserved .4. public void removeEmployee(int employeeId) { Employee employee = manager.Java EE Foundations 3.class. Thus in a remote interface.5 Removing Employees Removing the bean is a really simple process. manager. employeeId). the object must first be found and managed before it can be removed.find(Employee.remove(employee). The easiest method of doing this is to use the find() method to retrieve the entity before removal. } The entity is found in the persistence context with the find() method and then the remove method is used to remove it from the database. Pass a manged bean to the EntityManager’s remove() method and the data associated with that bean will be removed from the database.

setLastName("Doe"). The EntityManager’s merge() method will merge the unmanaged entity back into the data store based upon the primary key field. Employee managed = manager. employee. If the developer wants to make changes to database after the merge.4. The object represented by the variable is not managed. ENTITY BEANS 3.merge(employee). managed.setFirstName("John"). the last name in the database will be set to “Doe”. Inc All Rights Reserved .setFirstName() will do nothing to the database. } A couple of notes about merging. Recall the previous example. In this case the call to employee.setFirstName("John").CHAPTER 3.merge(employee). The object being merged makes an update on the database at the next flush() method or the end of the current transaction. public void updateEmployee(Employee employee) { manager. This time the employee object being merged is already attached within the EntityManager. The managed.6 Updating Employee Updating an entity is easy to accomplish.setLastName("Doe").merge(employee). Employee managed = manager. the managed variable must be used for that process. Therefore any changes made to either will update the entity in the database. Instead it creates a new entity that is returned by the merge. both “John” and “Doe” will be updated because both the employee and managed variables point to the same attached object within the EntityManager. Page 80 c 2010 n + 1. managed. In this instance. The merge() method does not attach the entity passed into the merge method. Employee managed = manager.setLastName() method modifies an attached object so when the transaction ends. The employee has already been merged and is still detached so the update does not change the data store.merge(employee). If the manager is already managing the object when the merge() is called then changes will be made to the managed object and the managed object will be returned by the function. employee.

createQuery("FROM Employee emp"). Query query = manager.4. The method returns a Query object that can be use to return a list of entities.Java EE Foundations 3.iterator(). The Query object returns the results using a raw List object which means the results need to be casted to the appropriate type.add((Employee)iter. Inc All Rights Reserved . } return employees. Page 81 c 2010 n + 1.getResultList(). } The completed session bean is shown on the next page 2 EJBQL is a SQL like language which can be used to select some set of entities from the database.next()). Below is an example of selecting all of the entities from the employee database table. List results = query.hasNext() ) { employees. while ( iter. Iterator iter = results. public List<Employee> listEmployees() { ArrayList<Employee> employees = new ArrayList<Employee>().7 Finding Multiple Employees The EntityManager’s createQuery() method is used in conjunction with an EJBQL2 statement to provide the capability to select multiple entities from the database. It will be covered in much greater depth in a later module.

ENTITY BEANS import javax.iterator().ejb. return employee. } public List<Employee> listEmployees() { ArrayList<Employee> employees = new ArrayList<Employee>().EntityManager. import javax.class.remove(employee). List results = query.next()).add((Employee)iter. Inc All Rights Reserved .getResultList().merge(employee). } public void updateEmployee(Employee e) { manager.persist(employee).Stateless. } } Page 82 c 2010 n + 1. employeeId). Query query = manager.CHAPTER 3. manager.PersistenceContext. } public Employee getEmployee(int employeeId) { Employee employee = manager. public void addEmployee(Employee employee) { manager. } public void removeEmployee(int employeeId) { Employee employee = manager.find(Employee.persistence. import javax. while ( iter.hasNext() ) { employees.find(Employee.persistence. public class EmployeeManagerBean implements RemoteEmployeeManager { @PersistenceContext(unitName="foobieDS") private EntityManager manager.class.createQuery("FROM Employee emp"). } return employees. Iterator iter = results. employeeId).

<?xml version="1. It has the database connection information using JDBC URL format.xml. Rather than creating a new connection whenever a connection is needed. In this case the JNDI for the datasource will be java:/FoobieDS. When a connection is generated from the Datasource one of the already pooled database connections is returned to the calling entity. JBoss uses an XML file with the naming convention *ds.net:5432/foobie</connection-url> <driver-class>org.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> <jndi-name>FoobieDS</jndi-name> <connection-url>jdbc:postgresql://db.5 DataSources In traditional JDBC database connectivity the DriverManager is used to create single connections to the database. Once the process using the connection finishes it closes the connection.Java EE Foundations 3. the Datasource pools the connections. Each process that needs a database connection must open a new connection which is resource intensive. When the close() method is called the connection with the database is not shut down.2</type-mapping> </metadata> </local-tx-datasource> </datasources> The datasource XML file contains a number of elements. It defines the size of the pool to use and it provides the JNDI naming information. Datasources are not directly instantiated by the developer.Driver</driver-class> <user-name>db</user-name> <password>mypassword</password> <min-pool-size>5</min-pool-size> <max-pool-size>100</max-pool-size> <metadata> <type-mapping>PostgreSQL 7. Once the process finishes the connection is closed. Page 83 c 2010 n + 1.nplus1. The process opens a connection to the database and uses it for the interaction with data store. Each container has a different mechanism for defining this relationship. Java EE container solves the problems of database connectivity by providing developers with Datasources. This creates a more scalable solution to handle heavy volume. Inc All Rights Reserved . The file must be placed into the server’s deployment directory. Instead they must be retrieved through a JNDI call. All Java EE containers provide a mechanism for binding a datasource to a JNDI name. With multiple processes accessing the database at different times. Below is an example of a JBoss datasource file for the Postgres database. The solution doesn’t scale well.postgresql. In addition the datasource settings for each database may be different. the resource hit becomes a factor. Datasources or similar to the DriverManager in that they represent a source of connections to the database. instead the connection is returned to the connection pool to be used by another entity.

For the persistence. A property is added to inform the entity manager that the database is Postgres so it knows what SQL dialect to use when making database calls.xml file to be picked up by the Java EE container. Below is an example of persistence.dialect" value="org. public class EmployeeManagerBean implements RemoteEmployeeManager { @PersistenceContext(unitName="foobieDS") private EntityManager manager.CHAPTER 3. Once the associations are complete the EntityManager has access to the datasource and the connections to the database for managing the entities. The mapping is accomplished by creating a configuration file that defines the relationship between the persistence unit and the datasource using the datasource’s JNDI name. It is building off the example from the previous section. Inc All Rights Reserved . The mapping is defined in a persistence.5.dialect. Page 84 c 2010 n + 1. The unit’s name can then be used when defining the EntityManager as shown previously. it must be placed within the META-INF directory of the deployed EJB jar file.PostgreSQLDialect"/> </properties> </persistence-unit> </persistence> The XML file defines a unit name and the JNDI look up for the datasource.xml file. <persistence> <persistence-unit name="foobieDS" transaction-type="JTA"> <jta-data-source>java:/FoobieDS</jta-data-source> <properties> <property name="hibernate. The defined persistence unit can then associated with any EntityManager.1 Persistence Units The persistence unit configuration is used to map the entity manager to a data store.hibernate. ENTITY BEANS 3.xml file for JBoss using the Postgres database.

jar"> <fileset dir="${build}"> <include name="**/beans/**"/> <include name="**/services/**"/> <include name="**/domain/**"/> </fileset> <metainf dir="${conf. This can be accomplished by adding an additional include statement to the jar’s fileset.xml"/> </metainf> </jar> </target> Page 85 c 2010 n + 1. In the example below the entity beans are contained in the domain subdirectory. Below is an example of using the tag to include the persistence.xml file. the beans were placed in a beans subdirectory and the associated interfaces were placed into a services directory. <target name="package-ejb" depends="build"> <jar jarfile="${dist}/foobie-ejb.jar"> <fileset dir="${build}"> <include name="**/beans/**"/> <include name="**/services/**"/> <include name="**/domain/**"/> </fileset> </jar> </target> The only thing left to do is include the persistence. <target name="package-ejb" depends="build"> <jar jarfile="${dist}/foobie-ejb. All that is necessary is for the entity beans to be added to the JAR file.xml file in the META-INF directory of the JAR file. Inc All Rights Reserved .6 Ant Build Files When building the ANT file for session beans. All of these files are then added to the EJB JAR file for deployment.xml file. The ¡metainf¿ ANT task allows the user to add files to the META-INF directory within the JAR file.ejb}"> <include name="**/persistence.Java EE Foundations 3. Below is an example of the target within the build.jar"> <fileset dir="${build}"> <include name="**/beans/**"/> <include name="**/services/**"/> </fileset> </jar> </target> The entity beans can be added to the same JAR file used for session beans. <target name="package-ejb" depends="build"> <jar jarfile="${dist}/foobie-ejb.

Inc All Rights Reserved .class META-INF/persistence. the resulting items would end up within the foobie-ejb. ENTITY BEANS Using the employee manager session bean and employee entity bean example from this module.CHAPTER 3.class net/nplus1/foobie/services/RemoteEmployeeManager. net/nplus1/foobie/beans/EmployeeManagerBean.class net/nplus1/foobie/beans/Employee.jar file.xml Page 86 c 2010 n + 1.

Java EE Foundations 3. Inc All Rights Reserved .7 Lab Activity Part 1. Page 87 c 2010 n + 1.

CHAPTER 3. ENTITY BEANS Page 88 c 2010 n + 1. Inc All Rights Reserved .

Chapter 4 Entity Beans Objectives • 89 .

The final type of relationship is the many to many relationship. object relationships can have directions associated with them. The tricky part is modeling these complex relationships within Java’s Object Oriented framework.1 Entity Bean Relationships The previous module on entity beans demonstrated the steps to map an entity bean to a table in the database. people will have multiple phone numbers. A person can have a list of committee objects it is associated with it. For this to work. A person object has a reference to the address object. The second type of relationship is the one to many relationship. but the address object does not necessarily have a reference back to the person object. Thus the two tuples provide an overlap of information. The one to one and one to many relationships can be either unidirectional or bidirectional 1 . Each employee belongs to a department within an organization and a department consists of a set of employees. If all programs only needed access to a couple of independent tables the problem the study of entity beans would be finished. An example of this is a person and committees. An example might be a person and his or her home address. They have a home number. Multiple people are members of a committee and a person can be members of multiple committees. ENTITY BEANS 4. a mobile number. There are several types of relationships. The best way to understand this concept is through an example. Relational databases were made so relationships could be defined between tables. the real world is considerably more complicated. Inc All Rights Reserved . The key is to set up Object relationships that are similar to the data relationships. And the department IT would have as one of its members John Doe. Unfortunately. An example of this type of relationship is a person and his or her phone number. A person object can hold a reference to an address object. another concept has to be thrown into the mix. 1 many to many relationships are always bidirectional Page 90 c 2010 n + 1. and even a work number. In this case multiple phone numbers are defined and each must be related back to the person entry with which it is associated. An example of a relationship is that between an employee and a department. The simplest type is a one to one relationship. Thus a record for John Doe would be associated with the department IT.CHAPTER 4. Each employee or department represents a “tuple”. In this case a single tuple in one table holds a relationship to a single tuple in another table. The committee object can have a list of people associated with it. What is a relationship and what type of relationships exist in a relational database? The definition of a relationship given on Wikipedia is a data structure which consists of a heading and an unordered set of tuples which share the same type. Generally people only have one home address and its tuple can be associated with the person’s tuple. This occurs when multiple tuples in one table are related to multiple tuples in another table. A person object can have a list of phone number objects associated with it. What does this mean? While database relationships exist. Generally. This is where a tuple in one table is related to multiple tuples in another table.

private String state. private String city. Let’s rework the example. private String lastName. Since each object holds a reference to the other. This is known as a unidirectional relationship because only one object holds a reference. // getter and setter methods } In this example the Person object has a reference to the Address and the Address holds a reference to the Person. private String state. // getter and setter methods } public class Address { private Person person. // getter and setter method } Notice that the Person object holds the Address object as a reference among it’s attributes. private Address address. private String streetAddress. private String lastName. Page 91 c 2010 n + 1. private String zipCode. public class Person { private String firstName. At the same time the Address does not have a reference to the Person object. private String city. private String zipCode. it is known as a bidirectional relationship. Inc All Rights Reserved . // getter and setter method } public class Address { private String streetAddress.Java EE Foundations public class Person { private String firstName. private Address address. The rest of the module guides the developer to modeling each of these relationships using entity beans.

/* getter and setter methods */ } public class Address { private int addressId. private String state. The objects would like the following. Otherwise a relational constraint will be violated which is not allowed within a database. Inc All Rights Reserved . public class Employee { private int employeeId. private Address address.1 One to One Unidirectional One to one unidirectional relationships are where one object holds a reference to another object. Page 92 c 2010 n + 1. Employee Table -------------------------id integer (pk) first_name varchar last_name varchar address_id integer (fk) Address Table ---------------------id integer (pk) address varchar city varchar state char The employee table and address table both have all the attributes necessary for each entry. In this case a tuple in the address table is associated with a tuple in the employee table.1. private String city. but that the relationship is only in one direction. An example of this would be to extend our Employee entity defined in a previous module to have a reference to an Address object. private String lastName. Foreign keys are a reference to a field in another table.CHAPTER 4. private String address. The schema for both tables is shown below. private String firstName. Below is some sample data. The Address object would not have a reference to the Employee. (pk) represents a primary key in and (fk) represents a foreign key. This is a relational field known as a foreign key. /* getter and setter methods */ } Each object can be mapped back to a data schema. ENTITY BEANS 4. The other object does not hold a relationship to the original object. The employee table has an extra entry for address id. It represents the primary key of another table and creates a direct link between the two tables2 . 2 The value of the foreign key must be part a valid tuple in the foreign table.

In this case Beth Smith is associated with the address 100 East Main St. KY. Sarah Jones likewise is associated with 12 Sunny Ln in New York City. Page 93 c 2010 n + 1. Inc All Rights Reserved . Louisville.Java EE Foundations Employee Table -----------------------------------------------------| id | first_name | last_name | address_id | -----------------------------------------------------| 10 | Beth | Smith | 1 | | 11 | Sarah | Jones | 3 | -----------------------------------------------------Address Table ------------------------------------------------| id | address | city | state | ------------------------------------------------| 1 | 100 East Main St | Louisville | KY | | 2 | 200 West Market St | Atlanta | GA | | 3 | 12 Sunny Ln | New York | NY | ------------------------------------------------Beth Smith is associated with the address defined by the id field 1.

CHAPTER 4. ENTITY BEANS Defining Relationship On Entity Bean Creating an Employee and Address entity follows the same procedure from the previous module as shown below. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; // what do we do with this? private Address address; /* getter and setter methods */ } @Table(name="address") public class Address { @Id @Column(name="id") private int addressId; private String address; private String city; private String state; /* getter and setter methods */ } The only question remains is what to do with the attribute address? Since the attribute is another entity bean, a one to one relationship must be defined between the two objects. Since the Address does not have a reference to the Employee so it is unidirectional in nature. The Persistence API provides a @OneToOne annotation to mark what type of relationship is being made. @OneToOne private Address address; Page 94 c 2010 n + 1, Inc All Rights Reserved

Java EE Foundations The API also provides a @JoinColumn annotation to specify the database column used to map the relationship. In this instance the @JoinColumn annotation would be applied to the Address attribute of the Employee. The annotations name attribute is used to mark the column used for the join. In this instance, the join column is the foreign key or address id in the employee table. @OneToOne @JoinColumn(name="address_id") private Address address; The final Employee class is shown below. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @OneToOne @JoinColumn(name="address_id") private Address address; /* getter and setter methods */ }

Page 95

c 2010 n + 1, Inc All Rights Reserved

CHAPTER 4. ENTITY BEANS

4.1.2 One to One Bidirectional
One to one bidirectional relationships occur when two objects hold references to one another. An example of this type of relationship is the employee and his security badge. The employee has a reference to the security badge and because the security badge can only be associated with a single employee it has a reference back to the employee. In this case the employee can gain information about the security badge and the security badge can return information about the employee. The objects would be similar to the following two classes. public class Employee { private int employeeId; private String firstName; private String lastName; private SecurityBadge badge; /* getter and setter methods */ } public class SecurityBadge { private int id; private int clearance_level; private Employee employee; /* getter and setter methods */ } Again, each object can be mapped back to the database schema. The schema for both tables can be shown below. Employee Table -------------------------id integer (pk) first_name varchar last_name varchar badge_id integer (fk) SecurityBadge Table -----------------------------id integer (pk) clearance_level integer

Notice that the relationship is defined in similar fashion to the Employee / Address relationship. The foreign key only exists on one table. Here is an example of where object relationships work differently from database relationships. In a database there is no directional distinctions. The relationship is always bidirectional. The join occurs because the tables share the single relationship. Below is some sample data from each table. Employee Table ---------------------------------------------------Page 96 c 2010 n + 1, Inc All Rights Reserved

Java EE Foundations | id | first_name | last_name | badge_id | ---------------------------------------------------| 10 | Beth | Smith | 1 | | 11 | Sarah | Jones | 3 | ---------------------------------------------------SecurityBadge Table ---------------------| id | clearance_level | ---------------------| 1 | 5 | | 2 | 4 | | 3 | 2 | ---------------------A casual review of the tables reveals that Beth Smith has a badge id of 1 which supports a badge with a clearance level of 5 while Sarah Jones has a badge id of 3 which relates to a badge with a clearance level of 2. Here it is worth noting that we can find out which employee is associated with a particular badge number directly from the Employee table. Confirming that all database relationships are bi-directional in nature.

Page 97

c 2010 n + 1, Inc All Rights Reserved

The @OneToOne annotation is used along with the @JoinColumn annotation. ENTITY BEANS Employee Bean Relationship The next step is setting up the two entity beans to hold relationships to one another. @Column(name="clearance_level") private int clearanceLevel. // what do we do with this? private SecurityBadge address. Inc All Rights Reserved . @Column(name="first_name") private String firstName. // what to do with this? private Employee employee. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. Page 98 c 2010 n + 1. @Column(name="last_name") private String lastName. /* getter and setter methods */ } @Table(name="security_badge") public class SecurityBadge { @Id private int id. /* getter and setter methods */ } The relationship between the Employee class and the SecurityBadge is similar to the one defined in the Employee/Address relationship. Below are the two entity beans without relationships defined. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId.CHAPTER 4.

Inc All Rights Reserved . @Column(name="last_name") private String lastName.Java EE Foundations @Column(name="first_name") private String firstName. /* getter and setter methods */ } Page 99 c 2010 n + 1. @OneToOne @JoinColumn(name="badge_id") private SecurityBadge badge.

@Table(name="security_badge") public class SecurityBadge { @Id private int id. the badge attribute defines the Employee’s side of the relationship. /* getter and setter methods */ } When dealing with a one to one bidirectional relationship. ENTITY BEANS SecurityBadge Bean Relationship What about the other side of the relationship? What needs to be done there? The @OneToOne annotation is used to mark the relationship between the two objects. First. The @OneToOne annotation supports a mappedBy attribute tell which attribute of the Employee class is used to define the relationship. the entity associated with the table that contains the foreign key relationship is the side of the relationship that gets the @JoinColumn annotation.CHAPTER 4. it is important to take away two concepts. Secondly. Looking at the Employee class. @Column(name="clearance_level") private int clearanceLevel. Thus “badge” is the mappedBy value. Page 100 c 2010 n + 1. @OneToOne(mappedBy="badge") private Employee employee. The only problem is the @JoinColumn is unavailable here because no join column exists in the SecurityBadge table. Inc All Rights Reserved . the other side needs a mappedBy attribute to point back to the attribute marked with the @JoinColumn.

/* getter and setter methods */ } public class PhoneNumber { private int id. It is important to be able to associate the employee with his disparate phone numbers. it doesn’t make much sense for the phone number to have a link back to the employee. private String lastName.Java EE Foundations 4. and cell phone number. /* getter and setter methods */ } In a relational database the relationship is fairly easy to configure. That way the phone number can be the multiple side of the relationship and the employee is anchored as the one side. work. Below is the table definition. private Set<PhoneNumber> phoneNumbers.3 One to Many Unidirectional The one to many unidirectional relationship occurs when one object holds a set of references to another type of object. Because each phone number is distinct the list of entities are managed as a set of data. Employee Table ----------------------------------------| id | first_name | last_name | Page 101 c 2010 n + 1. Employee Table -------------------------id integer (pk) first_name varchar last_name varchar Phone Number Table ---------------------------id integer (pk) type varchar phone_number varchar employee_id integer (fk) Below is some sample data for these two tables. public class Employee { private int employeeId. Inc All Rights Reserved . private String firstName. private String phoneNumber. private String type. The relationship is outline in the following two classes. At the same time. An example of this type of relationship is an employee and his phone numbers. The employee’s identification must be stored with each phone number.1. An employee can have multiple phone numbers such as home.

Sarah Jones has a work and fax number associated with her. work and home number. ENTITY BEANS ----------------------------------------| 10 | Beth | Smith | | 11 | Sarah | Jones | ----------------------------------------PhoneNumber Table ---------------------------------------| id | type | phone_number | employee_id | ---------------------------------------| 1 | cell | 555-1234 | 10 | | 2 | work | 555-1231 | 10 | | 3 | home | 555-1225 | 10 | | 4 | home | 555-1215 | 14 | | 5 | work | 555-1155 | 11 | | 6 | fax | 555-1071 | 11 | ---------------------------------------In this case Beth Smith has three phone numbers. Page 102 c 2010 n + 1. a cell. Inc All Rights Reserved .CHAPTER 4.

The PhoneNumber bean uses the concepts previously presented. Here the column name of the foreign key relating to the employee in the phone number table is used for the join. The @JoinColumn annotation is again used to accomplish this task. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. @Table(name="phone_number") public class PhoneNumber { @Id private int id. Page 103 c 2010 n + 1. @OneToMany private Set<PhoneNumber> phoneNumbers. @Column(name="first_name") private String firstName. @OneToMany @JoinColumn(name="employee_id") private Set<PhoneNumber> phoneNumbers. /* getter and setter methods */ } The multiplicity belongs in the Employee class and is represented by the Set¡PhoneNumber¿ attribute. The complete Employee class is shown below. The next step is to define how the two tables are joined. @Column(name="phone_number") private String phoneNumber. Here the @OneToMany annotation is used to mark the relationship between the two entities. private String type. Inc All Rights Reserved .Java EE Foundations Employee-Phone Number Relationship Now it is time to set up the entity relationships between the two entity beans.

CHAPTER 4. ENTITY BEANS @Column(name="last_name") private String lastName; @OneToMany @JoinColumn(name="employee_id") private Set<PhoneNumber> phoneNumbers; /* getter and setter methods */ }

Page 104

c 2010 n + 1, Inc All Rights Reserved

Java EE Foundations

4.1.4 Many to One Unidirectional
The many to one unidirectional relationship is the same type of relationship as a one to many unidirectional. The only difference is the many side holds a reference to the single side while the single side doesn’t have a reference to the many. An example of such a relationship would be an Employee / Location relationship. Multiple employees would belong to a single location. The Employee would be the many side of the relationship and the Location would be the single side. In this instance the Employee object would have a reference to the location, bu the location would not have a list of employees. The classes are shown below. public class Employee { private int employeeId; private String firstName; private String lastName; private Location location; /* getter and setter methods */ } public class Location { private int id; private String name; private String city; private String state; /* getter and setter methods */ } The table relationship would be the same as the one to many unidirectional tables with the employee table holding a reference to the location table. Employee Table -------------------------id integer (pk) first_name varchar last_name varchar location_id integer (fk) Example data is shown below. Employee Table ------------------------------------------------------| id | first_name | last_name | location_id | ------------------------------------------------------Page 105 c 2010 n + 1, Inc All Rights Reserved Location Table --------------------id integer (pk) name varchar city varchar state char

CHAPTER 4. ENTITY BEANS | 10 | Beth | Smith | 1 | | 11 | Sarah | Jones | 1 | ------------------------------------------------------Location Table -------------------------------------------------| id | name | city | state | -------------------------------------------------| 1 | Silicon Holler Office | Louisville | KY | | 2 | Sun Shopping Center | Shelbyville | KY | -------------------------------------------------In this example both Beth and Sarah belong to the Silicon Holler Office fulfilling the many to one relationship.

Page 106

c 2010 n + 1, Inc All Rights Reserved

Java EE Foundations Employee-Location Relationship It is time to define the relationships between the Employee and Location entities. Because the relationship is unidirectional, the Location class is set up as a regular entity bean. @Table(name="location") public class Location { @Id private int id; private String name; private String city; private String state; /* getter and setter methods */ } The join information is confined to the Employee class. In this case the relationship is defined with the @ManyToOne annotation. @ManyToOne private Location location; The @JoinColumn annotation is used to determine what field in the table joins the employee with the location table. In this case the location id is the field name. @ManyToOne @JoinColumn(name="location_id") private Location location; The entire Employee class is shown below. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName;

Page 107

c 2010 n + 1, Inc All Rights Reserved

find(Location.class. Location siliconHoller = manager. Two employee entities can not share the same address entity. ------------------------------------------------------| id | first_name | last_name | location_id | ------------------------------------------------------| 10 | Beth | Smith | | | 11 | Sarah | Jones | | ------------------------------------------------------Location Table -------------------------------------------------| id | name | city | state | -------------------------------------------------| 1 | Silicon Holler Office | Louisville | KY | | 2 | Sun Shopping Center | Shelbyville | KY | -------------------------------------------------Notice that the location id is not set for either Beth or Sarah. they look identical. Inc All Rights Reserved . In this example the employee entity Beth and location Silicon Holler is retrieved from the persistence context. ENTITY BEANS @ManyToOne @JoinColumn(name="location_id") private Location location. 10). Now consider the following code. In a one to many relationship the employee entities can share the same location.setLocation(siliconHoller).CHAPTER 4. /* getter and setter methods */ } Difference Between One to One and Many To One When comparing the Employee / Location tables and classes with those in the Employee / Address section above. It would update the database to the following. In fact the only real difference is one is marked with the @OneToOne annotation and one is marked with the @ManyToOne annotation. The location is then associated with Beth. beth.class. The best way to understand this principle is through an illustrative example. ------------------------------------------------------Page 108 c 2010 n + 1. What is the difference between these two annotations? The one to one annotation means that entity can only be directly related to one other entity.find(Employee. Consider the database for location and employee again. 1). Employee beth = manager.

1).class. ------------------------------------------------------| id | first_name | last_name | location_id | ------------------------------------------------------| 10 | Beth | Smith | 1 | | 11 | Sarah | Jones | 1 | ------------------------------------------------------Location Table -------------------------------------------------| id | name | city | state | -------------------------------------------------| 1 | Silicon Holler Office | Louisville | KY | | 2 | Sun Shopping Center | Shelbyville | KY | -------------------------------------------------If the relationship between employee and location were one to one then only a single location could be associated with the employee.setLocation(siliconHoller). If the relationship between the employee and location is one to many then the resulting update would occur in the database.Java EE Foundations | id | first_name | last_name | location_id | ------------------------------------------------------| 10 | Beth | Smith | 1 | | 11 | Sarah | Jones | | ------------------------------------------------------Location Table -------------------------------------------------| id | name | city | state | -------------------------------------------------| 1 | Silicon Holler Office | Louisville | KY | | 2 | Sun Shopping Center | Shelbyville | KY | -------------------------------------------------Now consider the following code. 10).find(Location. Location siliconHoller = manager. sarah.find(Employee. ------------------------------------------------------| id | first_name | last_name | location_id | Page 109 c 2010 n + 1. Employee sarah = manager.class. In this case the location would switch associations from Beth to Sarah as shown below. Inc All Rights Reserved .

CHAPTER 4. ENTITY BEANS ------------------------------------------------------| 10 | Beth | Smith | | | 11 | Sarah | Jones | 1 | ------------------------------------------------------Location Table -------------------------------------------------| id | name | city | state | -------------------------------------------------| 1 | Silicon Holler Office | Louisville | KY | | 2 | Sun Shopping Center | Shelbyville | KY | -------------------------------------------------In reality the one to one relationship and the many to one relationship are just tricks employed by the Java Persistence API to create the concept and not some constraint of the underlying database. Page 110 c 2010 n + 1. Inc All Rights Reserved .

/* getter and setter methods */ } public class Department { private int id. --------------------------------------------------------| id | first_name | last_name | department_id | 3 The Department Table --------------------id integer (pk) name varchar many to one bidirectional relationship is the same as the one to many bidirectional relationship Page 111 c 2010 n + 1.1. private String name. private String firstName. The employee has to hold a reference to the primary department id. private String lastName.5 One to Many Bidirectional The one to many bidirectional relationship3 occurs when a single entity holds a set of references to another type of entity. A department has multiple employee and needs to have access to the them. private Set<Employee> employees. /* getter and setter methods */ } The Employee class has a reference to the Department while the Department has a reference to the set of Employees that compromise the department. The schema is shown below.Java EE Foundations 4. The employee in turn belongs to a department and needs access to the department’s information. public class Employee { private int employeeId. Inc All Rights Reserved . In addition the multiple side of the relationship holds a reference to the single entity. Employee Table ---------------------------id integer (pk) first_name varchar last_name varchar department_id integer (fk) Below is some sample data for each table. Below is an example of both entities. private Department department. The union of these entities is easy to replicate in a relational database. An example of this form of relationship exists between a department and an employee.

Page 112 c 2010 n + 1. ENTITY BEANS --------------------------------------------------------10 | Beth | Smith | 1 | 11 | Sarah | Jones | 1 | 13 | Margaret | Thatcher | 2 | 12 | Janet | Doe | 1 | 14 | Ronald | Reagan | 2 | --------------------------------------------------------- | | | | | Department Table ----------------------------| id | name | ----------------------------| 1 | Information Technology | | 2 | Leaders Of Free World | ----------------------------In this example two departments are defined and Beth Smith. Sarah Jones.CHAPTER 4. Both sides of the relationship must be defined with annotations. and Janet Doe are all in the Information Technology department while Margaret Thatcher and Ronald Reagan are in the Leaders of Free World department. Inc All Rights Reserved .

Location relationship shown earlier. It has the same setup as the many to one relationship defined previously. Inc All Rights Reserved . @Column(name="last_name") private String lastName. @Column(name="first_name") private String firstName.Department relationship is the same as the Employee .Java EE Foundations Employee-Department Relationship The first step is to map the Employee to Department relationship. Since the employee entity table holds the relationship to the Department. @ManyToOne @JoinColumn(name="department_id") private Department department. a @JoinColumn annotation is needed to specify the column in the database used for the join. @ManyToOne private Department department. The Employee is the many side of the relationship. thus the @ManyToOne annotation is used to mark it. Page 113 c 2010 n + 1. What differentiates the two is that the Department class must be marked to complete the bidirectional link. /* getter and setter methods */ } Again. the setup for the Employee . @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. In this case the value is the department id @ManyToOne @JoinColumn(name="department_id") private Department department. Below is the Employee class with annotations.

CHAPTER 4. Thus the Department class must use the @OneToMany annotation to define its side of the relationship. /* getter and setter methods */ } Page 114 c 2010 n + 1. Below is the modified Department entity. @Table(name="department") public class Department { @Id private int id. private String name. In this case the Employee has a department attribute which maps back to the Department entity. @OneToMany private Set<Employee> employees. The second part is to provide the mapping to the other side of the relationship. Inc All Rights Reserved . the mappedBy property is used to map back to the attribute on the entity used for mapping. @OneToMany(mappedBy="department") private Set<Employee> employees. @OneToMany(mappedBy="department") private Set<Employee> employees. Similar to the one to one bidirectional relationship. ENTITY BEANS Department-Employee Relationship The Department .Employee relationship represents the one to many relationship.

/* getter and setter methods */ } Both classes maintain multiple references to each other.6 Many to Many Relationships The many to many relationship occurs when multiple entities contain references to multiple entities. An example would be the relationship between employees and projects. private String firstName. private String name. private String lastName. In a relational database. It maintains one to many relationships with both entities. public class Employee { private int employeeId. How can a many to many relationship be set up within that limitation? The answer is in using a joining table. The best way to understand the multiplicity is to examine an example scenario. /* getter and setter methods */ } public class Project { private int id. Therefore it is important for an employee to reference multiple projects and for project to reference multiple employees. The concept can be used to replicate many to many relationships. private Set<Project> projects.Java EE Foundations 4. Inc All Rights Reserved . private Set<Employee> employees.1. A joining table is an intermediary table between two entities. It needs to be replicated within the database using the two entities and a join table. At the same time a project generally worked on by a group of employees. Consider the employee to project relationship. An employee could be working on multiple projects at any one time. Employee Table ---------------------------id integer (pk) first_name varchar last_name varchar Project Table -------------------------id integer (pk) name varchar Page 115 c 2010 n + 1. relationships can only be of the type one to many.

But in its simplest form the projectemployee join table is the many side of the relationship between both the employee and project. ENTITY BEANS ProjectEmployee Join Table -------------------------id integer (pk) employee_id integer (fk) project_id integer (fk) In this case the join table holds references to both the employee and project table. This leads to the multiplicity between employees and projects. It creates a many to many relationship between project and employee tables. At the same time the Foobie Page 116 c 2010 n + 1. The same can be said for the projects. Inc All Rights Reserved . Thus one employee or project entry has multiple references in the projectemployee join table. Employee Table ----------------------------------------| id | first_name | last_name | ----------------------------------------| 10 | Beth | Smith | | 11 | Sarah | Jones | | 12 | Janet | Doe | ----------------------------------------Project Table ---------------------------| id | name | ---------------------------| 1 | Foobie Project | | 2 | My Favorite Project | ----------------------------ProjectEmployee Join Table -------------------------------| id | employee_id | project_id | -------------------------------| 100 | 10 | 1 | | 101 | 10 | 2 | | 102 | 11 | 1 | | 103 | 12 | 1 | | 104 | 12 | 2 | -------------------------------- Looking at the multiplicity first.CHAPTER 4. The Foobie Project with an id of 1 shows up three times in the join table. Beth whose id is 10 shows up twice in the join table. Beth’s id in the join table is associated with both project 1 and project 2. it is easy to see that each employee can enjoy multiple entries in the join table. It becomes clearer when looking at sample data.

The introduction of a join table complicates the annotations necessary for each class. Therefore the many to many relationship is established.Java EE Foundations project whose id is 1 has three employees associated with it. Page 117 c 2010 n + 1. and Janet. Beth. Inc All Rights Reserved . Sarah.

The joinColumns and invoiceJoinColumns both take a set of @JoinColumn annotations as arguments. inverseJoinColumns={@JoinColumn(name="employee_id")}) private Set<Employee> employees. The Java Persistence API provides a @JoinTable annotation for the many to many relationship. /* getter and setter methods */ } Page 118 c 2010 n + 1. It needs a @ManyToMany annotation to mark the type of relationship being used. @ManyToMany private Set<Employee> employees. the joinColumns property defines the column in the join table that relates to the Project entity’s @Id field. ENTITY BEANS Project-Employee Relationship First look at the Project entity. inverseJoinColumns={@JoinColumn(name="employee_id")}) private Set<Employee> employees. Inc All Rights Reserved . The new Project class is shown below. @Column(name="name") private String name. The joinColumns and inverseJoinColumns are used to define the join columns in the join table necessary to tie the two entities together. The @JoinTable annotation has three properties necessary for configuration. The invoiceJoinColumns property defines the column in the join table that maps to the Employee’s @Id field. The @JoinColumn annotation used in previous examples doesn’t work here because the Project entity is directly related to the join table.CHAPTER 4. Here is where the additional complexity is created. The name property provides the name of the join table. @ManyToMany @JoinTable(name="project_employee". @ManyToMany @JoinTable(name="project_employee". joinColumns={@JoinColumn(name="project_id")}. joinColumns={@JoinColumn(name="project_id")}. @Table(name="project") public class Project { @Id @Column(name="id") private int id.

Because all of the relationship information was done on the other side of the relationship in the Project class all that is necessary is a way to map the entity back to that definition.Java EE Foundations Employee-Project Relationship The other end of the relationship is the Employee entity. @Column(name="first_name") private String firstName. The final Employee class is shown below. @Column(name="last_name") private String lastName. @ManyToMany private Set<Project> projects. @ManyToMany(mappedBy="employees") private Set<Project> projects. The employees attribute on the Project entity provides the mapping. Inc All Rights Reserved . /* getter and setter methods */ } Page 119 c 2010 n + 1. Again the @ManyToMany attribute has to be applied to the project set attribute. The next step in the process is to set up the relationships. The mappedBy property on the @ManyToMany annotation can be used for the mapping. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. @ManyToMany(mappedBy="employees") private Set<Project> projects.

2 Multiple Relationship Considerations Multiple relationships provide unique challenges for the implementation.CHAPTER 4. Inc All Rights Reserved . Page 120 c 2010 n + 1. ENTITY BEANS 4. How does one order the multiple side of a relationship? How are relationships retrieved from the database? Is their a cascading effect when an entity is saved with the other side of the relationship? These questions are answered in the following sections.

The first is the entity’s field that needs to be sorted.util. @OneToMany @JoinColumn(name="employee_id") private List<PhoneNumber> phoneNumbers.Set data type is the perfect type for holding the data in a relationship. The @OrderedBy annotation is available to provide that functionality.util.util.Set data type with the java. DESC means the entities should be sorted in descending order. Below is an example of using @OrderBy to order the phone numbers by the phone number in descending order. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. the java. Inc All Rights Reserved .List data type when dealing with relationships. The second is the word ASC or DESC.Set class is a perfect representation. @Column(name="first_name") Page 121 c 2010 n + 1.util.2. it could prove very handy to have the list pre-ordered based upon an attribute of the object appearing in the list. @Column(name="last_name") private String lastName.Java EE Foundations 4. Therefore it is possible to replace the java. The argument passed to the annotation contains two words. ASC means the entities should be sorted in ascending order.1 Lists and Ordered By The java. Below the Employee entity is modified to replace Set¡PhoneNumber¿ with List¡PhoneNumber¿ as the data type for the relationship. @Column(name="first_name") private String firstName. Since database relationships are guaranteed to provide a distinct set of tuples. @Table(name="employee") public class Employee { @Id @Column(name="id") private int employeeId. The only problem with the set is it can’t be treated the same fashion as a list. /* getter and setter methods */ } If the data is in a list.

Inc All Rights Reserved . ENTITY BEANS private String firstName.CHAPTER 4. @Column(name="last_name") private String lastName. /* getter and setter methods */ } Page 122 c 2010 n + 1. @OneToMany @JoinColumn(name="employee_id") @OrderBy("phoneNumber DESC") private List<PhoneNumber> phoneNumbers.

out. the EntityManager doesn’t load them.getType() + ": " + number. @OneToMany(mappedBy="department". then the phone numbers are only retrieved from the database in the for loop. The cascade effect occurs when the many side of the relationship has its own set of relationships.LAZY) private Set<Employee> employees. This means that all related objects are fetched when the main entity is fetched from the database. Any attempt to access it will result in an exception. fetch=FetchType.Java EE Foundations 4. Inc All Rights Reserved .println(number.2 Fetch Type It is also possible to associate a fetch type with a relationship. } If the fetch type is set to eager.LAZY. Employee employee = entityManager.class.getFirstName() + " " + employee. for ( PhoneNumber number : employee. The fetch type determines how relationship entities are retrieved from the database. Since the phone numbers aren’t needed before then. @OneToMany(fetch=FetchType. The only problem with using eager in all cases is the cascade effect. The second is the “lazy” type. A lazy fetch means that that entities in a relationship are not loaded until the relationship is invoked by the main entity. Why would a developer ever need to use eager? Lazy seems like the obvious choice.out.EAGER) @JoinColumn(name="employee_id") private Set<PhoneNumber> phoneNumbers. The value of the fetch attribute must be either the FetchType.getPhoneNumbers() ) { System.find(Employee. When the employee class is loaded so are the phone numbers. When does this happen? The most common occurrence is when the entity bean is returned by a session bean. Each relationship annotation supports the fetch attribute. it is important to set the fetch type to eager.2.println("Phone numbers for " + employee. Below are two examples of defining a fetch type for a relationship annotation. The first is the “eager” type.getPhoneNumber()). System.EAGER or FetchType.getLastName()). If the fetch type is set to lazy. Therefore if an entity bean is going to be detached for any reason. There are two fetch types available to the developer. How does this work? Take the Employee and PhoneNumber relationship. No need to fetch data if it is never going to be used. 10). If the phone numbers have a relationship and they are set to eager then Page 123 c 2010 n + 1. the phone numbers are loaded from the data store when the entity is found in the first statement with the EntityManager’s find() method. The only problem is if the entity bean leaves the transaction and is detached from the EntityManager it can not access the relationship. Below is an example of how the Employee entity might be used to display a list of phone numbers to the console.

Page 124 c 2010 n + 1. A lot of entity beans could be created and loaded from the database from one simple find() call.CHAPTER 4. ENTITY BEANS those relationships will have to be loaded. In turn it could provide a bottle neck in performance. Inc All Rights Reserved .

All items in the relationship are merged back into the persistence context when the primary entity is part of a persist() call. Not only does it answer the question about what happens.Java EE Foundations 4. All items in the relationship are refreshed when the primary entity is refreshed by the EntityManager. If no cascade attribute is defined by the annotation then the default behavior is to have no cascading effects.3 Cascading Type What happens to the relationship entities when the main entity is persisted. merged.CascadeType.REMOVE}) private Set<Employee> employees.1: Cascade Values Any number of cascade values can be defined in a cascade attribute. and REMOVE cascade types. All items in the relationship are removed from data store when the primary entity is removed. Same as defining the relationship with PERSIST. Inc All Rights Reserved .2.1 Attribute PERSIST MERGE Description All items in the relationship are persisted when primary entity is part of a persist() call. fetch=FetchType. Below is an example of setting multiple values.EAGER. REFRESH REMOVE ALL Page 125 c 2010 n + 1. cascade={CascadeType. Table 4. REFRESH.PERSIST. or removed from the database? What happens if a refresh() is requested on the main entity? Each relationship annotation has a cascade attribute which can be set to handle this problem. it allows the developer to finely tune the type of cascading effect. MERGE. @OneToMany(mappedBy="employee". In this instance the PERSIST and REMOVE cascade effects are applied to the relationship. Any new items are persisted. The cascade attribute provides five settings shown in table 4.

private Date splitTime. Each split will have a number.1 Defining Entity Beans The first step is to define the database schema for storing the information. Each race will have a set of split times associated with it. Inc All Rights Reserved . private double distance. private int splitNumber. the distance traveled. Page 126 c 2010 n + 1. Each race will have a name and a date.3 Example Using Relationships The following example is a small set of code that would allow athletes to manage races and the split times from the race. private void String name. /* getter and setter methods */ } The next step is to covert them into entity beans with the Race entity in a one to many unidirectional relationship with the TimeSplit. public class Race { private int raceId. In this example the id fields are auto generated. private void Set<TimeSplit> splits. The following section walks through an implementation of the simple session bean. The example will put all of the logic for managing this data within a session bean. private void Date raceDate. ENTITY BEANS 4.3. /* getter and setter methods */ } public class TimeSplit { private int id. and the time of the split. Below are skeletons for the two classes. Race Table -------------------------id integer (pk) name varchar race_date time Split Time Table ---------------------------id integer (pk) split_number integer distance numeric split_time time race_id integer (fk) The second step is to define the Race entity and the TimeSplit entity from the database schema. 4.CHAPTER 4.

// getter and setter methods } @Entity @Table("split_time") @SequenceGenerator(sequenceName="split_sequence".Java EE Foundations @Entity @Table("race") @SequenceGenerator(sequenceName="race_sequence".TIME) private Date splitTime. generator="race-seq") private int raceId. private double distance. @Column(name="race_date") @Temporal(TemporalType. name="race-seq") public class Race { @Id @Column(name="id") @GeneratedValue(strategy=GenerationType. Inc All Rights Reserved . /* getter and setter methods */ } Page 127 c 2010 n + 1. generator="split-seq") private int id. name="split-seq") public class TimeSplit { @Id @GeneratedValue(strategy=GenerationType. private void String name. @Column(name="split_time") @Temporal(TemporalType.SEQUENCE. @Column(name="split_number") private int splitNumber.TIME) private void Date raceDate. @OneToMany @JoinColumn(name="race_id") private void Set<TimeSplit> splits.SEQUENCE.

edit. TimeSplit split). To simplify the process the manager should be able to handle adding and deleting races.CHAPTER 4. @Remote public interface RaceManager { public void addRace(Race race). public void updateSplit(TimeSplit split). ENTITY BEANS 4. In addition it should be able to add. Inc All Rights Reserved . public void removeSplit(TimeSplit split). public void removeRace(int raceId). } Page 128 c 2010 n + 1. and remove time splits for an individual race. public void addSplit(int raceId. public Race getRace(int raceId).3. The following interface defines the methods for the RaceManager.2 Race Manager The next step is the creation of the race manager which will be involved in managing races and the time splits.

persist(race).getSplits() ) { split. Inc All Rights Reserved . When a race is removed from the system there is no need for the time splits to stick around in the database. public void addRace(Race race) { // need to add splits if any exist if ( race. } In this instance any time splits associated with the race would be inserted into the database.getSplits() != null ) { for ( TimeSplit split : race. } } manager. @Stateless public class RaceManagerBean implements RaceManager { @PersistenceContext(unitName="foobieDS") private EntityManager manager. public void addRace(Race race) { manager. @OneToMany(cascade={CascadeType. // logic goes here } Since the original entity bean didn’t provide a cascade attribute work would have to be done to persist any splits. Below is code to add in the remove cascade effect. } Rewriting the @OneToMany annotation to allow for a persist cascade would allow the code to be simplified. The other method which makes a good candidate for cascading is the removeRace() method.Java EE Foundations Managing Races The RaceManagerBean would have the following structure. Page 129 c 2010 n + 1.persist(race).persist(split). The addRace() method can be simplified by removing the looping mechanism.PERSIST}) @JoinColumn(name="race_id") private void Set<TimeSplit> splits.

REMOVE}) @JoinColumn(name="race_id") private void Set<TimeSplit> splits. Remove the race and all associate time splits is as simple as removing the Race entity. raceId).remove(race). } Page 130 c 2010 n + 1.class.CascadeType.PERSIST. ENTITY BEANS @OneToMany(cascade={CascadeType. public void removeRace(int raceId) { Race race = manager.find(Race. manager. Inc All Rights Reserved .CHAPTER 4.

Once the time split is added to the race. Set<TimeStamp> splits = race. Below is an example of accomplishing these two goals. The code then looks up the race for associating it. Updating the time split is simple process since the Race is not affected by the modification. The Race object is retrieved from the persistence context and then the time split is added to the Race’s splits set. The addSplit() method provides a perfect illustration of the problem. Page 131 c 2010 n + 1. Secondly it needs to be added to the Race relationship. TimeSplit split) { // save the time split manager. public void addSplit(int raceId. The link between the Race and TimeSplit is maintained in the time split table. public void removeSplit(TimeSplit split) { manager.remove(split). The following pages provide the complete code for the example.Java EE Foundations Managing Splits The final section covers managing individual time splits for a race. Thus the Race doesn’t need to be modified. Removing a time split will automatically erase the link between the two entities. } In this example the manager persists the TimeSplit.add(split).merge(split). } What about the relationship? How is it updated to let it know that the time split is no longer part of the relationship? The answer resides with the underlying database structure. The difficult part of dealing with individual time splits is to make sure they are included in the relationship. This behavior also explains why inserting was a two step process. splits. The persistence of the TimeSplit inserts it into the table. but it doesn’t fill in the race id field. First the time split entity needs to be persisted. } Removing a time split shares similar simplicity. Inc All Rights Reserved . raceId).getSplits(). public void updateSplit(TimeSplit split) { manager.find(Race.class. The database is automatically updated with the relationship once the method is completed. // get race and add time split to relationship Race race = manager.persist(split). the race id field in the time split table is filled out.

Id. javax. generator="race-seq") private int raceId. javax. javax.GenerationType.GeneratedValue.TemporalType.CHAPTER 4.persistence.CascadeType. // getter and setter methods } Page 132 c 2010 n + 1.Temporal.SEQUENCE.REMOVE}) @JoinColumn(name="race_id") private void Set<TimeSplit> splits. javax.persistence.util.SequenceGenerator.Date.util.TIME) private void Date raceDate. javax. ENTITY BEANS Program Listing 1 Race Class import java. javax. javax.persistence. name="race-seq") public class Race { @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.OneToMany. javax. Inc All Rights Reserved . private void String name.CascadeType.PERSIST. @Entity @Table("race") @SequenceGenerator(sequenceName="race_sequence".persistence.persistence. @Column(name="race_date") @Temporal(TemporalType.persistence.persistence.JoinColumn.persistence. javax. import import import import import import import import import import import import javax.persistence.Table. @OneToMany(cascade={CascadeType. javax. import java.persistence.persistence.Column.persistence.Set.Entity. javax.

persistence. private double distance.persistence. javax.persistence.persistence.Id. javax.TIME) private Date splitTime.persistence. @Column(name="split_time") @Temporal(TemporalType. javax.Java EE Foundations Program Listing 2 TimeSplit Class import java. import import import import import import import import import javax.SequenceGenerator. generator="split-seq") private int id.Temporal.Column.persistence. /* getter and setter methods */ } Page 133 c 2010 n + 1. javax.GenerationType. javax. @Entity @Table("split_time") @SequenceGenerator(sequenceName="split_sequence". Inc All Rights Reserved .persistence.util. javax. name="split-seq") public class TimeSplit { @Id @GeneratedValue(strategy=GenerationType. javax.persistence.Entity.Table. javax.SEQUENCE.persistence. @Column(name="split_number") private int splitNumber.GeneratedValue.Date.TemporalType.

} Page 134 c 2010 n + 1. public void addSplit(int raceId. public void removeSplit(TimeSplit split).persistence. TimeSplit split). public void removeRace(int raceId). Inc All Rights Reserved . public Race getRace(int raceId).CHAPTER 4. ENTITY BEANS Program Listing 3 RaceManager Interface import javax. public void updateSplit(TimeSplit split). @Remote public interface RaceManager { public void addRace(Race race).Remote.

} public void updateSplit(TimeSplit split) { manager.class.EntityManager. splits. import javax. public void addRace(Race race) { manager. } public void removeRace(int raceId) { Race race = manager. Inc All Rights Reserved . // get race and add time split to relationship Race race = manager. } public void removeSplit(TimeSplit split) { manager.persistence.getSplits(). TimeSplit split) { // save the time split manager. raceId). Set<TimeStamp> splits = race.add(split). @Stateless public class RaceManagerBean implements RaceManager { @PersistenceContext(unitName="foobieDS") private EntityManager manager.Java EE Foundations Program Listing 4 RaceManager Interface import java.persist(race).Set. } public void addSplit(int raceId.persist(split).persistence. import javax. manager.util.find(Race.PersistenceContet. raceId). } } Page 135 c 2010 n + 1.class.remove(race).Stateless.remove(split).find(Race. import javax.persistence.merge(split).

CHAPTER 4. Inc All Rights Reserved . ENTITY BEANS Page 136 c 2010 n + 1.

Chapter 5 Querying Entity beans Objectives • 137 .

It uses the relationship between the classes rather than the underlying tables. It gains that independence because it is built on top of JDBC and uses standard SQL queries under the hood. Inc All Rights Reserved . Page 138 c 2010 n + 1.CHAPTER 5. Even with its good feature set it is not as powerful as native SQL. The SQL language was created to give users the ability to mine the database for information. The Java Persistence API provides a SQL like language for retrieving information through the object relational mappings of the defined entity beans. Unlike SQL it is portable across platforms. EJBQL is a full featured querying language that will meet most developer needs. SQL allows users to be able to pull data from multiple tables and across multiple relationships.1 Querying Entity Beans The great strength of databases are their ability to query the information stored within it. QUERYING ENTITY BEANS 5. It is an effective way to retrieve data from the data store.

Inc All Rights Reserved . Query objects are created by the EntityManager using one of three methods.1 Queries Query objects are used to retrieve data and objects from the persistence context.Java EE Foundations 5. The resulting Query object represents the query to the data store. Page 139 c 2010 n + 1. The rest of the module explores the Query object and the various types of query creation mechanisms.1: EntityManager Query Methods Each of these mechanisms for creating a query take some form of query as an argument.1. Method Query createQuery(String ejbql) Query createNamedQuery(String name) Query createNativeQuery(String sql) Description creates a query based upon the EJBQL statement provided creates query based upon named query annotated within an entity bean creates query based upon native SQL statement provided Table 5.1. Each are shown in table 5. They are the gateway to data retrieval and use the EJBQL to dictate what is returned.

Object class. Inc All Rights Reserved . executes query that updates the database and returns the number of rows affected.2.util.2: Query Methods These three methods cover the range of queries that might be attempted on a database. the Query object represents a query to the database. Method List getResultList() Object getSingleResult() int executeUpdate() Description executes query that returns multiple rows of data.1.List class executes a query that returns a single entity as a java. Providing a first taste of using the EJBQL language. The Query has three methods for executing the query and returning the results. Its methods are focused on retrieving results from the query.lang. They are shown in table 5.CHAPTER 5. The next step is to use one of these methods in an example. Table 5. Page 140 c 2010 n + 1.2 Query Result Methods As previously mentioned. The data is returned in the resulting java. QUERYING ENTITY BEANS 5.

The beginning of the EJBQL uses the “SELECT” keyword1 . Page 141 c 2010 n + 1. List results = query. -----------------------------------------------------------| employee_id | first name | last name | department | salary | -----------------------------------------------------------| 100 | John | Doe | Accounting | 50000 | | 101 | Jane | Doe | IT | 30000 | | 102 | Beth | Smith | IT | 90000 | ------------------------------------------------------------ EJBQL is different in that it isn’t dealing with table based data. The courseware uses the all caps format to highlight keywords in the EJBQL dialect. FROM Employee emp Thus the EJBQL query is as follows.createQuery("SELECT emp FROM Employee emp").3 Introduction to EJBQL In traditional SQL if a user wants the contents of the employee table the following query would be executed.Java EE Foundations 5. The “FROM employee” statement would tell the query engine which table to retrieve all columns. Query query = entityManager. SELECT * FROM employee The “SELECT *” would select all columns of the table being queried. 1 EJBQL is not case sensitive. SELECT emp The second part of the EJBQL defines which type of object is being retrieved and its associated variable. Select. It is dealing in objects. SELECT emp FROM Employee emp This statement tells the persistence context that it needs to pull all of the objects represented by the Employee entity. This EJBQL query can be used to create a Query object and return results in a list format. but combines it with the variable representing the object or objects being returned. or any combination of mixed case.1. The keyword SELECT can be used as select. The query would generate something like the following data. The query must start with selecting an object.getResultList(). Inc All Rights Reserved .

Below is an example of looping through the entities and displaying the contents. } The code would result in the following output Employee: John Doe (100) Employee: Jane Doe (101) Employee: Beth Smith (102) Page 142 c 2010 n + 1.createQuery("SELECT emp FROM Employee emp").hasNext()) { Employee emp = (Employee)iter. Iterator iter = results. Since the return type is the raw List type each item within the list are stored as java.getLastName() + " (" + emp.List object.getResultList(). Inc All Rights Reserved .getFristName() + " " + emp.util. while (iter.Objects which means they need to be cast to their appropriate type when pulled from the list. If no entities are returned by the query then the list will be empty.out. List results = query.getEmployeeId() + ")").next(). Query query = entityManager.println("Employee: " + emp.iterator(). QUERYING ENTITY BEANS List Results The method getResultList() is used to return the multiple entities that are retrieved from an EJBQL statement. The returned entities are stored within the java.util. The entities returned by the query are attached to the EntityManager meaning they are in a managed state when returned. System.CHAPTER 5. The entities retrieved will represent each tuple in the employee table.

SELECT emp.Java EE Foundations 5.address.4 Navigating Objects Entity beans with attributes defined with getter and setter methods can provide navigational capabilities within an EJBQL query.city FROM Employee emp In this example the emp variable once again represents the Employee class. The resulting query pulls the street name and city from the address associated with the employee.lastName FROM Employee emp In this instance the variable emp represents the Employee object. The navigation is not contained to just attributes of the Employee entity. SELECT emp. The following example assumes that the Employee and Address share a simple one to one relationship. Since it is an entity in a one to one relationship. In this case the query will return the Employee object’s firstName and lastName attributes. Page 143 c 2010 n + 1. If an attribute of the entity is itself an entity then that object can be navigated as well. Navigation is used with the emp variable to return attributes of the Employee object.streetName. The “emp.1.” notation.address.address” provide navigation to the address property of the Employee class. emp. emp. it can be navigated as well. A bean’s attributes can be accessed using the “. Inc All Rights Reserved .firstName.

} In this instance the query is returning the Employee’s attributes first name and last name. } It would result in the following output.println("First Name = " + firstName). The array’s index is based upon the order in which each attribute appears within the select line. System.firstName.hasNext() ) { Object [] data = (Object [])iter. Inc All Rights Reserved . emp. List results = query. Iterator iter = results. while ( iter. Query query = entityManager. When multiple objects are returned by the select statement they are managed within the returned list as an object array. System. First Name = John Last Name = Doe Page 144 c 2010 n + 1. It would generate the following output. System.createQuery( "SELECT emp.next(). Below is an example of retrieving multiple attributes from an EJBQL query. First Name = John First Name = Jane First Name = Beth In addition.out.next().iterator().hasNext() ) { String firstName = (String)iter. Thus in this instance the zero index would hold the first name and the one index would hold the last name.firstName FROM Employee emp").getResultList(). while ( iter.iterator(). QUERYING ENTITY BEANS Returning Entity Attributes Entity navigation allows an entity to return attributes from the EJBQL query.getResultList(). Query query = entityManager.println("First Name = " + data[0]).createQuery( "SELECT emp. Iterator iter = results. List results = query. a query can return multiple attributes or entities.out.println("Last Name = " + data[1]).lastName FROM Employee emp"). Each of these attributes are returned as Objects.out. A single attribute returned can be treated as a simple object by the returned List.CHAPTER 5.

Java EE Foundations First Name = Jane Last Name = Doe First Name = Beth Last Name = Smith Page 145 c 2010 n + 1. Inc All Rights Reserved .

The last name field must have the value “Doe”. But will only return the rows that match the condition specified in the WHERE clause. -----------------------------------------------------------| employee_id | first name | last name | department | salary | -----------------------------------------------------------| 100 | John | Doe | Accounting | 50000 | | 101 | Jane | Doe | IT | 30000 | ------------------------------------------------------------ The WHERE clause in EJBQL provides the same functionality as the WHERE clause in SQL.CHAPTER 5. the query will return all of the columns from the employee table. Inc All Rights Reserved . the WHERE clause is used to narrow the search to a specific subset of data. The following is an example of a SQL query that would generate a smaller set of data. Page 146 c 2010 n + 1. SELECT * FROM employee WHERE last_name = ’Doe’. The query would result in the following record set. In this example.2 WHERE Clause In SQL. It allows the query to narrow the results. The following sections explore the WHERE clause and the various methods for narrowing the results of a Query. QUERYING ENTITY BEANS 5.

getFirstName()).println("First Name = " + emp.iterator().hasNext() ) { Employee emp = (Employee)iter. Secondly.getEmployeeId()).out. Non numerical literals must be encapsulated with the single quote character.out. literals can be used while doing comparisons. Inc All Rights Reserved .println("Last Name = " + emp. List results = query. while ( iter. Like the SELECT statement. System. ID = 102 First Name = Beth Last Name = Smith Page 147 c 2010 n + 1. System.2. } The code would result in the following output.Java EE Foundations 5. In this example.getResultList(). navigation of entities can be used in the WHERE clause.firstName=’Beth’").createQuery( "SELECT emp FROM Employee emp WHERE emp.1 EJBQL WHERE Clause Below is the first example of an EJBQL statement. A couple of things to note.println("ID = " + emp.getLastName()). Iterator iter = results. Employee entities that have the first name of Beth are returned. SELECT emp FROM Employee emp WHERE emp. Below is an example of using the WHERE clause above in a code example.out.firstName=’Beth’ The addition of the WHERE clause limits the number of Employee entities that are returned by the query.next(). System. Query query = entityManager.

out. dynamicName). .createQuery( "SELECT emp FROM Employee emp WHERE emp.2 Dynamic WHERE Clause Values Most WHERE clauses do not use literals to narrow the results.println("ID = " + emp. query.getLastName()). System. The second is the dynamic value to use for the replacement. Below is a full example using dynamic queries.getEmployeeId()). When using dynamic variables their is no need to put the variable in quotes. The first is a String value that represents the variable name for the replacement.next(). Query query = entityManager. The variable is replaced with a dynamic value at run time. In this instance the variable “name” is replaced with “Beth”. QUERYING ENTITY BEANS 5. Inc All Rights Reserved .println("Last Name = " + emp.firstName=:name In this example.out. Iterator iter = results.out.firstName=:name"). System.setParameter("name". } The above example results in the following output. System.setParameter("name". Reworking the previous example a variable can be used to replace the literal.2. String dynamicName = "Jane"..getFirstName()). ID = 101 First Name = Jane Last Name = Doe Page 148 c 2010 n + 1. The placeholder variable must start with a : and can be used in place of any literal value.getResultList(). The Query object provides a setParameter() method allowing the developer to set the value at run time. while ( iter.println("First Name = " + emp. query.iterator(). SELECT emp FROM Employee emp WHERE emp. Instead of using the literal value in the WHERE statement a placeholder variable can be use instead. "Beth").. List results = query. The setParameter() method takes two arguments.CHAPTER 5. It is much more common to use dynamic values that can be determined at run time. the variable :name is used to replace the literal ‘Beth’.hasNext() ) { Employee emp = (Employee)iter.

3.Date(). while ( iter.getEmployeeId()).getLastName()). query.out.Java EE Foundations Date Types The only exception to this simple replacement mechanism is the use of Date values. Recall the java. The TemporalType enumeration contains a reference to each of the three types shown in table 5.startDate = :date").DATE TemporalType.out. time. } Page 149 c 2010 n + 1.iterator().Date start = new java. Iterator iter = results. java. Query query = entityManager.DATE).3: Temporal Types Below is an example of using the temporal type to specify the replaced value is a date.TIMESTAMP Description Specifiy the database data type “date” Specifiy the database data type “time” Specifiy the database data type “timestamp” Table 5. The setParameter() method can take a third argument that allows the developer to set which of the three date mechanisms to use when doing a comparison.next().util.println("Last Name = " + emp. System.out. TemporalType.createQuery( "SELECT emp FROM Employee emp WHERE emp. Passing the temporal data type tells which value to use for the comparison. and time stamp.hasNext() ) { Employee emp = (Employee)iter. System. Enumerated Value TemporalType. List results = query. System.getResultList(). Inc All Rights Reserved . Thus the Date can be used to represent three different date and time mechanisms in the database. start. They are date.getFirstName()).Date class is a wrapper around a date and time.util.println("First Name = " + emp.TIME TemporalType.util.setParameter("date".println("ID = " + emp.

EJBQL supports five other comparison symbols shown in table 5.println("First Name = " + emp.2.out. } The example would result in the following output: ID = 100 First Name = John Last Name = Doe ID = 102 First Name = Beth Last Name = Smith Page 150 c 2010 n + 1.createQuery("SELECT emp FROM Employee emp " + "WHERE emp.4 Operator ¡ ¿ ¡= ¿= ¡¿ Description less than greater than less than or equal greater than or equal less than or greater than which is also not equal Table 5. System.println("ID = " + emp. 40000).getLastName()).out.getFirstName()).getEmployeeId()). Query query = entityManager. Below is an example of using greater than on the employee’s salary field. Inc All Rights Reserved .getResultList().hasNext() ) { Employee emp = (Employee)iter. System. System.salary > :salary").next().out.setParameter("salary".3 Comparison Symbols Up til this point all of the examples have used equality for reducing the resulting entities returned. QUERYING ENTITY BEANS 5.4: Comparison Symbols Any of these can be used when comparing two values. List results = query. query.println("Last Name = " + emp. Iterator iter = results.CHAPTER 5. while ( iter.iterator().

Table 5. two comparisons are being made. The variables fname and lname are set by using multiple setParameter() calls.setParameter("fname".firstName = :fname AND e.2. The AND and OR operators can be used multiple times within a query. SELECT e FROM Employee e WHERE e. Similar to SQL all logical operators are tested.Java EE Foundations 5. The previous example can be made more explicit through their use. Table 5.5: Logical Operators The introduction of logical operators also introduces the concept of multiple parameters within the EJBQL statement. query. Inc All Rights Reserved . There is no limit to the number of comparison join operations.lastName = :lname OR emp.lastName = :lname In this example. The first is comparing the employee’s first name and the second is comparing the employee’s last name. It is only true when the comparison evaluates to false.firstName = :fname AND e. Greater control over which logical operators can be wielded by using parenthesis. query. It is only true when both comparisons are true. Page 151 c 2010 n + 1. Used on a simple comparison. Parenthesis have higher precedence and can be used to group multiple logical operators. It is only true when either of the comparisons are true. The logical operators can be used to combine multiple comparisons into one query. "Beth"). In this case.5 provides a list of logical operators Operator AND OR NOT Description Used with two comparisons. the query would match if the first name and last name matched or the employee’s salary was less than the specified amount.setParameter("lname". This is possible as long as the variables used for each parameter is unique. SELECT e FROM Employee e WHERE e.4 Logical Operators A query’s selection can be more finely detailed with the use of logical operators. Used with two comparisons. "Smith").salary < :salary The question is how does this query work? AND and OR have the lowest priority but they are executed in the order that they appear.

Page 152 c 2010 n + 1. Inc All Rights Reserved . the NOT operator only operates on a single comparison and is only true if the comparison evaluates to false. 40000).CHAPTER 5. John Doe.getResultList(). List results = query. In this example the Employee entities which are returned have a salary greater then 40000 and a first name which is not Beth.setParameter("name". query.firstName = :name)"). "Beth").createQuery("SELECT emp FROM Employee emp " + "WHERE emp.salary < :salary While the AND and OR operators introduce multiple comparisons.salary > :salary AND NOT(emp.firstName = :fname AND e. query.lastName = :lname) OR emp. QUERYING ENTITY BEANS SELECT e FROM Employee e WHERE (e. Query query = entityManager.setParameter("salary". Only one element in the database fits that description.

The following are all matches of the query. fun funny fun loving this is a lot of fun I have a funny story to tell Page 153 c 2010 n + 1. The EJBQL version of LIKE provides two pattern matching characters. The % is used to represent any sequence of characters. Inc All Rights Reserved . All of the following would match the LIKE statement. "Smith%" The Smith% matches any string that starts with the characters “Smith”. The is used to represent any single character.2. All of the following are possible matches it sit Fit proffit this is a test of it A final example of the % is using it at the beginning and end of a string. "%fun%" The example would match any string that contains the characters fun within it. Smith Smiths Smithers Smithereens Smith and the chocolate factory Here is another example of the % character. The best way to understand how it works is to look at a couple of examples.5 Like Operator The LIKE operator is similar to the SQL version of LIKE in that it allows matching of patterns rather than absolute values when querying the database. "%it" This example matches any string that ends with the characters it.Java EE Foundations 5.

println("ID = " + emp. The second example matches on any 4 letter name that begins with the character J.getEmployeeId()).next(). } In this instance the LIKE statement would match Smith and return Beth Smith’s information from the database.setParameter("lname". Any of the following would match. sit fit hit bit What if a developer needs to match either of these special characters within the LIKE statement? The character can be used to escape either of the characters.out. "%ith%"). query.out. "_it" It would match any of the following words.getLastName()). QUERYING ENTITY BEANS The character is used to represent a single character. List results = query.out. System.getResultList(). test % this is a test %43% test % test end of the test % Below is a complete example of using a LIKE statement. Here is an example of using it.hasNext() ) { Employee emp = (Employee)iter.iterator(). Iterator iter = results.createQuery("SELECT emp FROM Employee emp " + "WHERE emp. Page 154 c 2010 n + 1. System.println("Last Name = " + emp. Query query = entityManager.println("First Name = " + emp.lastName LIKE :lname"). "%test \%%" In this instance it would match any string that contains the substring “test %”.CHAPTER 5. Below is an example of using the to escape the percent sign.getFirstName()). Inc All Rights Reserved . System. while ( iter.

println("ID = " + emp.out. List results = query. } It would return the information for both John and Jane Doe.createQuery("SELECT emp FROM Employee emp " + "WHERE emp.println("First Name = " + emp. Inc All Rights Reserved . Iterator iter = results.hasNext() ) { Employee emp = (Employee)iter. System.println("Last Name = " + emp. System.Java EE Foundations Query query = entityManager.iterator().getLastName()).getFirstName()). "J___").out.firstName LIKE :fname"). System.next().getEmployeeId()). query.getResultList().setParameter("fname". Page 155 c 2010 n + 1.out. while ( iter.

The first is the IN clause. The final operator is the IS EMPTY test. Inc All Rights Reserved . The IN operator can be combined with NOT to exclude multiple values. SELECT emp FROM Employee emp WHERE emp. Any string values must be encapsulated with single quotes.projects IS EMPTY In this example. If none exist then the result will be an empty Set. ’Jane’) SELECT emp FROM Employee emp WHERE emp. QUERYING ENTITY BEANS 5. 51000) In the first example the query will match any employee whose first name is either Beth. It is used to match when an object’s attribute is NULL within the database.2. ’Sarah’. SELECT emp FROM Employee emp WHERE emp. It also matches one to one or many to one relationships which haven’t been defined.6 Other Operators EJBQL provides three other mechanisms for testing values.firstName IN (’Beth’. The values must be encapsulated within parenthesis and are comma separated. Page 156 c 2010 n + 1. IN provides the developer with the ability to test equality against multiple values. ’Sarah’) In this instance the query will match any employee whose first name is NOT Beth or Sarah.department IS NULL In this instance the query will return any employee whose department information hasn’t been defined. The IS EMPTY operator exists because the relationship can not be null.department IS NOT NULL In this case. It is used to test if the many side of a relationship has been created. the query will return any employee who has a defined department. In the second example the query will match anyone with a salary of either 50000 or 51000. SELECT emp FROM Employee emp WHERE emp. SELECT emp FROM Employee emp WHERE emp.CHAPTER 5. or Jane. A second operator is the IS NULL operator. Like the IS NULL operator it can be used with NOT to create the IS NOT EMPTY operator.firstName NOT IN (’Beth’. SELECT emp FROM Employee emp WHERE emp. Sarah. it will find any employees who do not have a project object associated with it. The IS NULL operator can be used in combination with the NOT operator to return all values which have been defined.salary IN (50000.

SELECT emp FROM Employee emp ORDER BY emp. SELECT emp FROM Employee emp ORDER BY emp. but it can be made explicit by using the ASC (ascending) modifier. It would be incredibly useful to the developer if the results could be preordered using the query rather than manually sorting. If any two employee’s share a last name it will then order by the first name. But what of the ordering of those items returned.2. emp.firstName ASC Page 157 c 2010 n + 1.lastName. SELECT emp FROM Employee emp ORDER BY emp.Java EE Foundations 5. Jane Doe John Doe Beth Smith Of course the ASC and DESC modifiers can be applied to each parameter to the ORDER BY operation. SELECT emp FROM Employee emp ORDER BY emp.firstName In this instance the list will order by last name.salary ASC It is also possible to sort on multiple columns when ordering.lastName DESC.lastName ASC SELECT emp FROM Employee emp ORDER BY emp. EJBQL provides an ORDERED BY operator to specify the attributes upon which to sort the query.salary DESC Ascending order is the natural ordering of the ORDER BY statement. emp. Inc All Rights Reserved . The DESC is short for descending order. The second query would return employees ordered by the salary with the lowest salary first. What if the developer wanted to return employees with highest salary to lowest? Or if the developer wanted to return the last name in reverse alphabetical order? The DESC modifier is used to reverse the natural ordering of a list.7 Ordering Results EJBQL provides the ability to query the data store for multiple entries.salary The first query would return all of the employees order alphabetically by last name.lastName SELECT emp FROM Employee emp ORDER BY emp. SELECT emp FROM Employee emp ORDER BY emp. The query would result in the following order of employees.lastName DESC SELECT emp FROM Employee emp ORDER BY emp.

Beth Smith Jane Doe John Doe Page 158 c 2010 n + 1. Inc All Rights Reserved . QUERYING ENTITY BEANS The final example would return the following results.CHAPTER 5.

The top salary is 90000. System.salary) FROM Employee emp SELECT MIN(emp. double topSalary = (Double)results.6 provides a list of these functions.0 The example can be expanded to show a list of employees that make the top salary. Operator COUNT() AVG() SUM() MIN() MAX() Description Returns the number of entities returned by query Returns the average value of an entity’s attribute for all entities returned by the query Returns the sum of an entity’s attribute for all entities returned by the query Returns the smallest value of an entity’s attribute for all entities returned by the query Returns the largest value of an entity’s attribute for all entities returned by the query Table 5.out. Page 159 c 2010 n + 1. The final example returns the lowest salary of all employee entities in the data store. All of these aggregate functions provide a single valued response and should be treated as a single result. The code would result in the following output. Object results = query.createQuery( "SELECT MAX(emp.6: Aggregate Functions Below are three examples using these functions.8 Aggregates The EJBQL language provides five functions for aggregating query data.Java EE Foundations 5.getSingleResult(). Table 5.2. Query query = entityManager. SELECT COUNT(emp) FROM Employee emp SELECT AVG(emp. Inc All Rights Reserved .salary) FROM Employee emp The first example returns the count of all employee entities in the database.println("The top salary is " + topSalary).salary) FROM Employee emp"). The second one returns the average salary of all employee entities.

out. List results = query. Iterator iter = results.salary = :top"). } The output is shown below. Object results = query.setParameter("top".CHAPTER 5. topSalary). Inc All Rights Reserved .hasNext() ) { Employee emp = (Employee)iter.out. query = entityManager.println("Top Salary Is $" + results). System.createQuery( "SELECT MAX(emp.println("Owned By " + emp.getResultList(). System. QUERYING ENTITY BEANS Query query = entityManager.next().iterator(). Top Salary Is $90000.0 Owned By Beth Smith Page 160 c 2010 n + 1.salary) FROM Employee emp").getSingleResult().createQuery( "SELECT emp FROM Employee emp WHERE emp.getFirstName() + " " + emp.getLastName()). query. int topSalary = (Integer)results. while ( iter.

This section takes a look at some other features that are available through the Java Persistence API. the module has been focused on returning sets of entity data or their attributes from the data store using the EJBQL language.3 Other Persistence Functionality Up to this point.Java EE Foundations 5. Inc All Rights Reserved . Page 161 c 2010 n + 1.

while ( iter. Paging needs two pieces of information to work.getFirstName() + " " + emp. Second. EJBQL provides a paging mechanism that allows the developer to divide the results into smaller segments called pages. a starting point for the page and the number of elements to return. } In the example the pageNumber and pageSize are set first. The second variable is pageSize and it is used to determine the maximum number of elements to return.setMaxResults(pageSize). QUERYING ENTITY BEANS 5.hasNext() ) { Employee emp = (Employee)iter. Below is an example of using the paging capabilities.iterator(). When dealing with a lot of data.next(). The Query element provides two methods to fulfill this requirement. This value is zero based.149 are returned by the query. List results = query.setFirstResult(pageNumber * pageSize).getResultList(). setFirstResult() and setMaxRequests(). Inc All Rights Reserved . query.CHAPTER 5.out.1 Paging Results There are two problems when dealing with large data sets.createQuery("SELECT emp FROM Employee emp"). int pageSize = 50. query. First it takes a lot of time to return all of the data.println("Name = " + emp. it would be very convenient to break the data into smaller chunks.3. int pageNumber = 2. The next 50 elements are returned by the query. The display mechanism only needs to provide the page number and page size to be able to loop through a long list of employees 50 at a time. In this example the value is set to 2. Therefore 0 is the first element in the result set. setFirstResult() determines what index to start returning results. Query query = entityManager. Therefore elements 100 . The query will return less if there is less than the maximum number or rows specified. it can be a bit unweildly to manage. The query page index is set to page number times the page size which is 100. System. setMaxRequests() determines the maximum number of elements to return. Especially when trying to display the data to the end user.getLastName()). Page 162 c 2010 n + 1. The pageNumber is a variable used to determine which page of data to display. Iterator iter = results.

It defines the EJBQL query.Java EE Foundations 5. This is the name invoked at query creation.setParameter("name". The second is the query. Page 163 c 2010 n + 1.setParameter("name".class). If multiple classes define a getByLastName query. List results = query.firstName = :name") }) @Entity public class Employee { // Employee class defined here } The @NamedQueries annotation is the wrapper allowing multiple @NamedQuery annotations to be defined.lastName = :name"). "Smith"). It is invoked at Query creation by the EntityManager using the createNamedQuery() method. Access the predefined query is a simple process. The @NamedQuery annotation has two attributes. @NamedQueries({ @NamedQuery(name="getByLastName". Below is an example of using the annotations to create the named queries.getResultList(). List results = query. query. query="SELECT emp FROM Employee emp WHERE emp. query="SELECT emp FROM Employee emp WHERE emp. Employee. The named query can then be invoked when the Query is created by EntityManager. Query query = manager.2 Named Queries If the same query on an entity is created in multiple locations it leads to the possibility of injecting errors into the code base. Query query = manager. The @NamedQueries and @NamedQuery annotations are used to associate queries to a particular entity bean. the entity class can be passed to the EntityManager.getResultList().3. query. Inc All Rights Reserved . The first is the name. The Java Persistence API provides a mechanism called named queries to centralize frequently used entity queries. Query query = manager.createNamedQuery("getByLastName".createNamedQuery("getByLastName". "Smith"). Below is a full example of invoking a named query. Employee.class).createNamedQuery("getByLastName"). Especially if the query is changed in one location without being modified everywhere. @NamedQuery(name="getByFirstName". The curly brace is used to define the array of @NamedQuery annotations.

setParameter("name". System. while ( iter.println("Name = " + emp.CHAPTER 5.iterator().next(). Iterator iter = results.getResultList(). Inc All Rights Reserved .getFirstName() + " Smith"). "Smith").hasNext() ) { Employee emp = (Employee)iter.out. } Page 164 c 2010 n + 1. QUERYING ENTITY BEANS query. List results = query.

getResultList().createNativeQuery("SELECT first_name. System.iterator(). Query query = manager. Therefore the Java Persistence API provides a mechanism for specifying native SQL statements. last_name " + "FROM employee WHERE employee. Native queries can be defined at Query creation using the creatNativeQuery() method. last_name " + "FROM employee WHERE employee.next().emp_id < 100"). The only question is how to deal with the results to the query? The results are dealt with in the same manner as querying multiple attributes of an entity. it is a cross platform query language. Query query = manager.Java EE Foundations 5.hasNext() ) { Object [] data = (Object [])iter.println("Last Name = " + data[1]). Inc All Rights Reserved .createNativeQuery("SELECT first_name. It can’t perform every task the native SQL language of the database can.emp_id < 100"). } Page 165 c 2010 n + 1. List results = query. Below is an example of such a method call. They are returned as an Object array.out. Iterator iter = results. while ( iter.3 Native Queries While the EJBQL language is extensive.3.

Inc All Rights Reserved . QUERYING ENTITY BEANS Page 166 c 2010 n + 1.CHAPTER 5.

Chapter 6 Transactions Objectives • 167 .

Either the work completes and the shared resource is updated or the work fails and nothing is changed with the shared resource. TRANSACTIONS 6. Page 168 c 2010 n + 1. The purpose of a transaction is two fold.CHAPTER 6. The transaction ensures that data is left in a consistent state. It also provides the shared resource with a method for handling system failures where units of work can be left in a partially completed state. Inc All Rights Reserved .1 Transactions In software development a transaction is an independent unit of work that modifies information stored in a shared resource. The unit of work is an all or nothing action. First it allows multiple processes to access a shared resource simultaneously without corrupting the data.

If the unit of work has multiple steps. isolated. Inc All Rights Reserved . Either it works or it doesn’t work. Isolation means that each transaction is independent of any other transaction. Any dependence between transaction would break this rule.1 ACID Transaction The most common resource which utilizes transactions is the database.Java EE Foundations 6. databases utilize the ACID principles for maintaining a consistent state. Once the transaction completes then the database transitions to a new consistent or harmonious state. consistent. That means that state remains unchanged until the transaction is completed. Each transaction must maintain these principles to be considered a transaction. Which means previous steps are undone or rolled back to their previous state before the transaction began. Atomicity means that each unit of work must be an all or nothing proposition. then any failure will cause the entire unit of work to fail. There is no partial transaction completion. Consistency means that the database remains in a state of agreement with itself between each transaction. Durability means that the data store is guaranteed to maintain the modification once the transaction has been concluded. To ensure data is not corrupted. and durable. The data is either changed or it is not changed. What is a harmonious or consistent state? It means that each field in the database has the correct data type and that all relationships meet the referential integrity rules.1. Because each transaction is independent they can be queued and executed one at a time by the data store. Any system failures will not result in a loss of the changes made by the transaction. ACID stand for atomic. Page 169 c 2010 n + 1.

The J2EE container provides declarative transactional management through the use of annotations. @Stateless public class MyManagerBean implements RemoteMyManager { @TransactionAttribute(value=TransactionAttributeType. it allows the developer to focus on the business logic rather than ancillary services. • Required • Supports • Requires New • Mandatory • Not Supported • Never Below is an example of marking a method with the @TransactionAttribute annotation.CHAPTER 6. If an exception is raised by the method then the container injects code to rollback the transaction before the exception is passed back up the stack. The value must be on of the values from the TransactionAttributeType enumeration.SUPPORTS) public void doSomeStuff() { // interacts with database } } The @TransactionAttribute has one attribute named value. Inc All Rights Reserved Page 170 . Once the method finishes executing the container injects code to commit the transaction. Container managed transactions provide a number of benefits. When the method is invoked the container injects transaction initialization code before the method is executed. How does the container provide transaction management? It starts when the developer associates a @TransactionAttribute annotation to a method on a session EJB. The meaning of supports will be covered in the next section.1. c 2010 n + 1. In this instance it associates the supports scope with the method. Once a transaction is declared the transactions are handled by the container and not the developer. the API contains a simple mechanism for managing transactions. The @TransactionAttribute specifies the scope of the transaction associated with the method. TRANSACTIONS 6.2 J2EE Container Provides Transaction Management Since the J2EE container was built to provide enterprise services to the developer. How do the transactions work? The container provides a wrapper for the invoked method. The J2EE platform supports six transactions scopes. Secondly. First it reduces the complexity of code by freeing the developer from having to manage transactions manually.

Requires New The REQUIRES NEW value tells the transactional manager of the container that the invoked method must have its own transaction. Inc All Rights Reserved .3 Six Transaction Scopes The TransactionAttributeType enumeration has six values associated with it. It can not join another transaction. Therefore if the method caller is already involved in a transaction then the annotated method will join the transaction and any failure within the method will result in a rollback of the data.Java EE Foundations 6. Mandatory The MANDATORY value tells the transaction manager that the invoked method must be included in an already existing transaction. It will not create a new transaction if one doesn’t already exist. The next six sections provide a break down of each scope level and how it effects the transactional capabilities of the method. the current transaction is suspended and the new transaction takes over. it will generate a new transaction regardless of the caller’s transaction state. In this case. Page 171 c 2010 n + 1. Each scope provides a different transactional behavior. Once the method finishes and the new transaction is complete. When the calling code invokes the annotated method within a transaction. Required The annotation set with the value of TransactionAttributeType.1. If the method caller is not involved in a transaction then the annotated method will behave like any other method invocation. If the calling code segment is already involved in a transaction then the current method call would join the already engaged transaction. If the caller is not involved in a transaction.REQUIRED tells the transaction manager that method must be involved in a transaction. In fact if the method is invoked without an already existing transaction then an Exception will be raised by the container. then the container is required to create a new transaction for the duration of the annotated method. Supports The SUPPORTS value tells the transaction manager that the method does not have to be involved in a transaction. the initial transaction is resumed. but if it is part of a transaction then it isn’t a problem.

Both stateful and stateless session beans can use any of these transactional scopes. If the method caller is not involved in a transaction then the annotated method will behave like any other method invocation.CHAPTER 6. Message driven beans on the other hand can only use either the REQUIRED or the NOT SUPPORTED values. Never The NEVER value tells the transaction manager that the annotated method must never be invoked within a transaction. TRANSACTIONS Not Supported The NOT SUPPORTED value informs the transaction manager that any running transaction must be suspended until after the annotated method completes. One final note on transactional scope and EJBs. Page 172 c 2010 n + 1. Any attempt to call this method while a transaction is running will cause the container to raise an exception. The transaction is not propagated to the invoked method. Inc All Rights Reserved .

1. Page 173 c 2010 n + 1.4 Exceptions and Transactions With a better understanding of the various transaction scopes that can be applied to an EJB. Inc All Rights Reserved . it is time to explore how transactions are effected by raised exceptions.Java EE Foundations 6.

TRANSACTIONS Runtime Exceptions and Transactions Runtime exceptions are caused by programming errors and are descendants of the RuntimeException class. With a stateless session bean. In addition the EJB instance where the exception occurred is immediately dereferenced and marked for garbage collection. The stateful session beans are a different story. Inc All Rights Reserved .CHAPTER 6. the stateful session bean is no longer accessible by the client application. Page 174 c 2010 n + 1. Any conversational state with the bean is lost and any attempt by the client to call the destroyed bean will result in a runtime exception. When a runtime exception occurs within a transaction the transaction is rolled back to its original state. When an exception calls. the bean is immediately removed from the pool of available beans before it is dereferenced. The most common form of runtime exception is the NullPointerException that arises when an object is accessed which hadn’t been instantiated previously. Any future calls to the session bean will use another bean from the pool. Within the J2EE container all of the EJBExceptions and derivatives are runtime exceptions.

The @ApplicationException annotation can be associated with a custom exception to transform it into a transaction ending exception. Checked exceptions derive from the base Exception class. } } The exception will cause a transaction rollback because the rollback attribute of the @ApplicationException annotation has been set to true. A common checked exception is the IOException class which is raised when I/O errors occur. It is possible to force a custom checked exception to cause a transactional rollback. } public FoobieException(String message. It allows the developer to correct the problem and retry the failed code without rolling back the entire transaction. Page 175 c 2010 n + 1. When a checked exception is raised within a transaction. the transaction is NOT rolled back. } public FoobieException(String message) { super(message). cause). All custom exceptions which extend from the Exception class are additional examples of a checked exception.Java EE Foundations Checked Exceptions and Transactions Checked exceptions are exceptions that are raised when a known error condition occurs. Below is an example of creating a custom exception. @ApplicationException(rollback=true) public class FoobieException extends Exception { public FoobieException() { super("Foobie Failure"). Exception cause) { super(message. Inc All Rights Reserved . The annotation has a rollback attribute that must be set to true to make the exception force rollbacks.

They are dirty reads. The JDBC driver specification defines five different isolation levels.1.1 shows the five isolation levels. it is important to understand transaction isolation levels. non-repeatable and phantom reads.CHAPTER 6. Inc All Rights Reserved . Below is a JBoss datasource XML file modified to set the isolation level to TRANSACTION REPEATABLE READ. This can occur when transaction Y commits a change while X is still running. <?xml version="1.5 Isolation Levels In managing transactions. Isolation Level TRANSACTION NONE TRANSACTION READ UNCOMMITTED TRANSACTION READ COMMITTED TRANSACTION REPEATABLE READ TRANSACTION SERIALIZABLE Description Runs queries outside of transactions. It is the isolation level which determines what problems are allowed during a transaction. non-repeatable reads and phantom reads. Transaction prevents dirty reads but allows non-repeatable and phantom reads. and phantom reads. Phantom reads occur when transaction Y inserts rows that satisfy the results of a WHERE clause in transaction X. TRANSACTIONS 6.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> Page 176 c 2010 n + 1. The isolation level determines how databases are locked during a transaction. The entries go from least secure and fastest in performance down to most secure and slowest. non-repeatable. Table 6. Transaction prevents dirty and non-repeatable reads while phantom reads can occur. Table 6. With JBoss all that is necessary is a minor modification to the datasource XML file. This means that the same SELECT query run twice in transaction X would return a different row count. Transaction prevents dirty. To understand how the isolation level works it is important to know the three problems transactions have in a multi-user database environment. A non-repeatable read occurs when a SELECT query in transaction X can be run multiple times and get different results. All problems can occur Transaction allows dirty.1: Isolation Levels Configuring the isolation level for the J2EE environment is container specific. making it appear that new records are magically appearing. A dirty read occurs when transaction X can read the results of transaction Y before Y is committed. It is considered a dirty read because Y can rollback the transaction which would make the data retrieved from X bad.

postgresql.2</type-mapping> </metadata> </local-tx-datasource> </datasources> Page 177 c 2010 n + 1. Inc All Rights Reserved .Java EE Foundations <jndi-name>FoobieDS</jndi-name> <connection-url>jdbc:postgresql://db.Driver</driver-class> <transaction-isolation>TRANSACTION_REPEATABLE_READ</transaction-isolation> <user-name>db</user-name> <password>mypassword</password> <min-pool-size>5</min-pool-size> <max-pool-size>100</max-pool-size> <metadata> <type-mapping>PostgreSQL 7.nplus1.net:5432/foobie</connection-url> <driver-class>org.

Inc All Rights Reserved . TRANSACTIONS Page 178 c 2010 n + 1.CHAPTER 6.

Chapter 7 JMS And Message Driven Beans Objectives • 179 .

JMS needs to provide guaranteed message delivery. Since JMS represents a common API. 1 There are 3rd party JMS vendors Page 180 c 2010 n + 1. It doesn’t matter where the receiver is even located. The actual implementation is left up to the specific vendor. the messages and the messaging system are portable between implementations. What does it mean to have asynchronous communication? It means that the message sender does not wait for the receiver to actually receive the message. JMS AND MESSAGE DRIVEN BEANS 7. JMS provides two different messaging techniques. It accomplishes this task by storing the message locally and sending it to its destination. Instead the sender can continue on with whatever task needs to be accomplished next. In the case of JMS and JNDI the vendor is usually the J2EE container1 . Inc All Rights Reserved . the vendor is the database creator. the publish / subscribe and point to point mechanisms. the sender will resend the stored message at a later time. The receiver can resides in a separate thread or VM from the sender. JMS is similar to JDBC and JNDI in that they are each a set of interfaces that define a set of functionality.CHAPTER 7. JMS as previously noted is an asynchronous form of communication. In the case of JDBC. The receiver’s job is to wait around until the sender sends it a message. It will continue to store the message until the receiver verifies that it has received the message. If the receiver doesn’t receive the message for some reason like network outage.1 Java Messaging Service Java Messaging Service or JMS for short is a set of interfaces defining a method for delivering asynchronous communication. Since the sender does not wait to gain confirmation that the receiver actually receives the message.

messages are pushed to consumers through the use of Topics. In effect.Java EE Foundations 7. Page 181 c 2010 n + 1. In JMS. Each resource subscribes to a services and when a message is published it goes out to all of the subscribers. the publisher is broadcasting a message to all of the subscribers. A Topic is a programming construct that allows publishers to send out a JMS message to multiple destination.1 Publish / Subscribe The publish subscribe model allows multiple resources to receive messages.1. Inc All Rights Reserved . The subscribers subscribe to the Topic. Any message delivered to the topic by the client is then delivered to each subscriber. The topic is used to decouple the publisher from the subscriber.

2 Point to Point The point to point model allows a single resource to receive a given message. It will only send the next message after the previous message has been delivered. messages are pushed to the consumers through the use of a Queue. Page 182 c 2010 n + 1. The publisher sends the message and is is received by one receiver. Inc All Rights Reserved . Messages are stored in the Queue in the order they are received. JMS AND MESSAGE DRIVEN BEANS 7. the sender and receiver are decoupled by the Queue. A Queue is a programming construct that allows the publisher to send out a JMS message that will be received by a single entity.1. Like the publish / subscribe model and Topics. In JMS.CHAPTER 7.

the steps necessary to receive a JMS message are introduced. Afterward. Inc All Rights Reserved .2 Message Delivery The next sections walk through the process of connecting to a Topic and Queue along with the necessary steps for sending a JMS message. Page 183 c 2010 n + 1.Java EE Foundations 7.

jboss. Page 184 c 2010 n + 1. It can be found within the jms folder within the deploy directory.jmx. JMS AND MESSAGE DRIVEN BEANS 7. the topic can be retrieved from the JNDI.name=FoobieTopic"> </mbean> Any services added to the jbossmq-destinations-server.xml will be available on service restart.destination:service=Topic.mq.1 Topics Topics in the J2EE world are created and managed by the J2EE container. Topic foobie = (Topic)context.CHAPTER 7. Once defined. Inc All Rights Reserved . In JBoss the resource is stored within the topic tree.server. In JBoss.lookup("topic/FoobieTopic"). Thus the following code could be used to retrieve the topic from the JNDI server. Below is an example of adding a new topic “FoobieTopic” <mbean code="org.2. Each container provides its own mechanism for creating a Topic. Context context = new InitialContext().mq. the user needs to add an entry into the jbossmqdestinations-service.Topic" name="jboss.xml file.

lookup("TopicConnectionFactory"). The following code combines both steps. Page 185 c 2010 n + 1. \TopicConnection connection = factory. Below is an example of retrieving the connection factory from the JNDI server. The start() method is used to start the flow of connections. The factory can be used to create a connection to the messaging service. By default the flow of messages is on when the connection is created. Since the connection factory is platform dependent.createConnection().Java EE Foundations TopicConnection The first step in sending a message to a topic is to access the TopicConnectionFactory object. the factory resides in the root path and can be found under the name TopicConnectionFactory. The factory is used to retrieve a connection to the messaging server.close(). TopicConnectionFactory factory = (TopicConnectionFactory) context. TopicConnectionFactory factory = (TopicConnectionFactory) context. The connection has two methods for handling the flow of messages. The stop() method is used to turn off the flow of messages. Inc All Rights Reserved . In JBoss. each container has its own defined JNDI path for the factory. connection. Context context = new InitialContext(). Similar to datasources.createConnection(). When finished using a TopicConnection the developer should as with every other resource close the connection.lookup("TopicConnectionFactory"). the TopicConnectionFactory resource is retrieved from the JNDI server. It provides an interface to the underlying container implementation. It is similar to the DriverManager in JDBC. \TopicConnection connection = factory. Context context = new InitialContext().

TopicSession session = connection. These are variables that are ignored by the J2EE standard. 2 some J2EE Servers ignore the standard and may make use of these arguments. TopicSession session = connection. 0).CHAPTER 7.AUTO ACKNOWLEDGE.AUTO_ACKNOWLEDGE). or subscribers. It can be used to generate JMS messages. It is recommended that the values be set to true and 0. The TopicSession creates an interactive session with the messaging service. Please check the server documentation to determine if the J2EE server uses them. Below is an example of how to retrieve a TopicSession. The second is an integer value that determines acknowledgment mode. Page 186 c 2010 n + 1.createTopicSession(true. JMS AND MESSAGE DRIVEN BEANS Topic Sessions The TopicConnection is used to retrieve a TopicSession. The first is a boolean value that determines if the session is part of a transaction.createTopicSession(false. these values must be set. The createTopicSession() method takes two arguments. The general form is false and Session. 2 In a client application. Right now it is time to focus on the publishers and subscribers. Session. publishers. Inc All Rights Reserved . A discussion of JMS messages will be covered in detail later.

lookup("TopicConnectionFactory"). Page 187 c 2010 n + 1. // create session from connection TopicSession session = connection.createPublisher(topic). The publisher can then be used to distribute message to subscribers through the associated Topic. \\ create context Context context = new InitialContext().createConnection(). // create publisher and associate with topic TopicPublisher publisher = session. Below is an example of the steps necessary to create a TopicPublisher. TopicConnection connection = factory. 0).lookup("topic/FoobieTopic"). // lookup the topic Topic topic = (Topic)context.createPublisher(topic). TopicPublisher publisher = session. // lookup connection factory and get topic connection TopicConnectionFactory factory = (TopicConnectionFactory) context. Inc All Rights Reserved .Java EE Foundations TopicPublisher The TopicPublisher object is used to deliver messages to a Topic.createTopicSession(true. When the TopicPublisher is created it must be associated with a Topic.

Context context = new InitialContext().CHAPTER 7.createSubscriber(topic). Topic topic = (Topic)context.lookup("TopicConnectionFactory"). TopicConnection connection = factory. JMS AND MESSAGE DRIVEN BEANS TopicSubscriber The TopicSubscriber object is used to receive messages from a Topic. Below is an example of all the code needed to create a TopicSubscriber as a client application. TopicSession session = connection. Notice it uses the same steps as the TopicSubscriber.lookup("topic/FoobieTopic"). a listener can be associated with the subscriber. When the message is received the listener is called to handle the processing of the JMS message. Page 188 c 2010 n + 1. // create subscriber and associate with topic TopicSubscriber subscriber = session. TopicSubscriber subscriber = session. TopicConnectionFactory factory = (TopicConnectionFactory) context. Inc All Rights Reserved . This makes sense because the process of connecting to the JMS messaging service should be similar for the sender and receiver.AUTO_ACKNOWLEDGE).createConnection(). Session.createTopicSession(false. Once the TopicSubscriber is created. When the TopicSubscriber is created it must be associated with a Topic to receive messages.createPublisher(topic).

server. the same mechanism used for Topic creation is used for Queue creation.2.destination:service=Queye.lookup("queue/FoobieQueue").jboss.mq. Queues like their brother the Topic is created and managed by the J2EE container.Queue" name="jboss.2 Queues The Topic is the glue between publish and subscribers. They are also configured differently for each container. Queue foobieQ = (Queue)context. <mbean code="org.Java EE Foundations 7. Inc All Rights Reserved .jmx. Context context = new InitialContext(). Below is the code used to retrieve the Queue.name=FoobieQueue"> </mbean> The queue can be retrieved from the JNDI server under the queue subdirectory. Page 189 c 2010 n + 1. In JBoss.xml file to create a Queue named “FoobieQueue”.mq. The Queue provides the same service in a point to point system. Below is the modified entry in the jbossmq-destinations-server.

lookup("queue/FoobieQueue"). Context context = new InitialContext(). Page 190 c 2010 n + 1.createSender(queue). Table 7. \\ create context Context context = new InitialContext().1: Mapping Of Topic To Queue Equivalents Since the Queue and Topic behave similarly. The code below shows the replacements. Below is an example of creating the QueueSender. The next step is to replace the retrieval of the Topic with the Queue.createQueueSession(true. // lookup connection factory and get topic connection QueueConnectionFactory factory = (QueueConnectionFactory) context. Once the Queue is returned from JNDI.CHAPTER 7. // create session from connection QueueSession session = connection. Topic Class TopicConnectionFactory TopicConnection TopicSession TopicPublisher TopicSubscriber Queue Class QueueConnectionFactory QueueConnection QueueSession QueueSender QueueReceiver Table 7. 0). In this example the QueueConnectionFactory is returned rather than the TopicConnectionFactory. Inc All Rights Reserved . That means the steps for sending and receiving messages are the same.1 show the mapping of Topic objects to Queue objects. The same steps can be used to replace the TopicSubscriber with the QueueReceiver. With it a QueueConnection can be retrieved and a QueueSession can be instantiated.lookup("QueueConnectionFactory"). JMS AND MESSAGE DRIVEN BEANS Using Queues The Queue works in identical fashion as the Topic.createConnection(). // create publisher and associate with topic QueueSender sender = session. The only difference is in the name of the classes. The QueueSender is configured in the same manner as the TopicPublisher. // lookup the topic Queue queue = (Queue)context. QueueConnection connection = factory. it can be used to retrieve a QueueSender rather than the TopicPublisher. the code for using a Queue is almost identical to the code for a topic.

Inc All Rights Reserved .createReceiver(topic).lookup("QueueConnectionFactory").lookup("queue/FoobieQueue"). // create subscriber and associate with topic QueueReceiver reciever = session.createConnection(). Page 191 c 2010 n + 1.AUTO_ACKNOWLEDGE).Java EE Foundations QueueConnectionFactory factory = (QueueConnectionFactory) context. QueueSession session = connection. QueueConnection connection = factory. Queue queue = (Queue)context. Session.createQueueSession(false.

Page 192 c 2010 n + 1. the discussion has focused on creating the mechanisms necessary for sending and receiving objects.3 JMS Messages Up till this point. Inc All Rights Reserved .CHAPTER 7. JMS AND MESSAGE DRIVEN BEANS 7. Now it is time to turn the focus to creating and sending the JMS messages between the various elements.

Instead of having a simple object based method like a Map. Queue queue = (Queue)message. 28).getJMSTimestamp().getJMSMessageID().setJMSPriority(3). message. Table ?? provides a list of common methods. These provide standard getter and setter methods for various header values. Inc All Rights Reserved .getIntProperty("age"). the Message provides a get / set method pair based upon data type. String messageId = message. These properties are an excellent way to send meta-data between applications when developing a JMS solution.setStringProperty("myName". The first are header methods. Setting application level properties and retrieving them are easy. Topic topic = (Topic)message.1 Message Interface The javax.getJMSDestination().Message interface defines a the set of methods necessary for sending a message over JMS.getStringProperty("myName"). 5-9 is high priority Topic or Queue that consumer should send a reply Table 7. "Beth").jms.3. String name = message.setIntProperty("age". message.getJMSDestination(). int age = message.Java EE Foundations 7. message. The values are stored in a key/value name pair similar to the java. the Message interface supports application level properties.util. Each primitive data type has its own property method call.Map class. The most commonly used headers are shown in table ?? Header JMSDestination JMSMessageID JMSTimestamp JMSPriority JMSReplyTo Description The Topic or Queue that sent the message Unique String value used to identify the message long value (time in milliseconds) that marks when message was sent int value from 0 to 9: 0-4 is a normal priority. long ts = message. These are custom properties that can be set by the developer at run time. Page 193 c 2010 n + 1.2: JMS Header Values Retrieving and setting header information from a message is straight forward. In addition to header values. The methods are broken into three categories.

Therefore the TopicSession or the QueueSession object must be used to instantiate the concrete implementation of the interface.4: JMS Message Types Since each of these message types are themselves interfaces. Header TextMessage ObjectMessage MapMessage BytesMessage StreamMessage Description The message consists of a single text String The message consists of a serializable Object The message consists of a Map like construct The message consists of a byte array The message consists of a primitive stream of data Table 7. the concrete implementations of each interface are not directly available. Inc All Rights Reserved .createTextMessage(). That is because the JMS API provides five extensions of the Message interface based upon message type that is to be used. ObjectMessage. Once created the data can be filled out and the message sent.3. JMS AND MESSAGE DRIVEN BEANS Header String getStringProperty(String key) void setStringProperty(String key. they can not be instantiated directly. int value) long getDoubleProperty(String key) void setDoubleProperty(String key.4 provides a list of messaging interface types. Table 7.2 JMS Message Types Notice that none of the Message’s interface methods define setting and retrieving information regarding the primary message. Page 194 c 2010 n + 1. Because it is platform independent.3: JMS Properties 7. Object value) Description Gets and sets property of type String Gets and sets property of type String Gets and sets property of type String Gets and sets property of type String Table 7.CHAPTER 7. and MapMessage types. TextMessage message = session. Below are examples of using the TextMessage. String value) int getIntProperty(String key) setIntProperty(String key. double value) Object getObjectProperty(String key) void setObjectProperty(String key.

setString("lastName". any object sent using the MapMessage must be serializable. Page 195 c 2010 n + 1. 32). The object must be serializable because it could potentially be transported across the network. message. message. message. 33. "Smith"). Each primitive data type .Java EE Foundations TextMessage The TextMessage is the simplest form of JMS message. It has a setText() method which is used to define the text to send.createObjectMessage(). MapMessage message = session. Inc All Rights Reserved . String and object have their own method calls.setString("firstName".createMapMessage(). Date now = new Date(). It allows the developer to send a series of key driven name/value pairs. Order somePurchaseOrder = new Order(). MapMessage The MapMessage is a more complicated JMS message. "Beth").setObject(somePurchaseOrder).23). message. message. now). message. TextMessage message = session.setText("some important message").setObject("date".createTextMessage(). Like the ObjectMessage. ObjectMessage The ObjectMessage is another simple form of JMS message. It takes any serializable object and sends it to the waiting consumer.setInt("age". ObjectMessage message = session.setDouble("amount". message. It takes a single string and transports it to waiting consumers.

Below is an example of sending a message to a Topic. the connection factory can be retrieved. Once the message’s content is filled. To be able to send a JMS message.createConnection(). /* get topic and connect it to a publisher Topic topic = (Topic)context.publish(text). Below is an example of sending to a queue.lookup("TopicConnectionFactory").lookup("QueueConnectionFactory"). With the context.createQueueSession(true. Page 196 c 2010 n + 1. The connection factory is used to get a connection to the messaging services. /* close connection *? connection. The publish() method is used by topic publishers and the send() method is used by queue senders. The session is used to create the message. 0).lookup("topic/FoobieTopic"). It is connected to the session through the user of a publisher.CHAPTER 7. TopicConnection connection = connectionFactory. Once all of the messages are delivered the connection to the JMS server is closed. TopicConnectionFactory connectionFactory = (TopicConnectionFactory) context. JMS AND MESSAGE DRIVEN BEANS 7. a message is needed and a topic to publish it. TopicSession session = connection. text. The first step is to get a context to the JNDI server.3 Sending JMS Message Once the message is created by the session and the content is filled. it is sent by the publisher using the publish() method. The connection is used to open a JMS session.createTextMessage().setText("some important message"). TopicPublisher publisher = session.close().createTopicConnection(). /* create message */ TextMessage text = session. QueueSession session = connection.createPublisher(topic). The topic is retrieved from the JNDI server. QueueConnectionFactory factory = (QueueConnectionFactory) context. Inc All Rights Reserved .3. 0). Context context = new InitialContext(). Time to review all of the elements within this code block. the publisher or sender is used to send off the message. QueueConnection connection = factory. /* code to get the connection session */ Context context = new InitialContext(). /* send message */ publisher.createTopicSession(false.

createTextMessage(). connection.createSender(queue). /* send to queue */ sender.setText("some important message"). TextMessage text = session. text. Page 197 c 2010 n + 1.send(text).close(). Inc All Rights Reserved .lookup("queue/FoobieQueue"). QueueSender sender = session.Java EE Foundations Queue queue = (Queue)context.

Inc All Rights Reserved .CHAPTER 7.getString("name"). The listening object must implement this interface. System.getText()).out. If the listener could receive multiple message types then code must be supplied to handle the various types. JMS is an asynchronous messaging system. The safest way is to test incoming types before casting.println("Message for you sir: " + txtMsg. public class MultiFoobieListener implements MessageListener { public void onMessage(Message message) { if ( message instanceof TextMessage ) { TextMessage txtMsg = (TextMessage)message. That means that the publisher of a message does not wait for the message destination to receive the message before continuing on with processing.out. String msg = mapMsg. } else if ( message instanceof MapMessage ) { MapMessage mapMsg = (MapMessage)message. To be able to handle all message types the incoming message is cast as the base Message interface. Thus the receiver must be in either a separate thread or another virtual machine.println("Message for you sir: " + txtMsg. Each receiving process must wait or “listen” for any incoming messages.: } } } Page 198 c 2010 n + 1. JMS AND MESSAGE DRIVEN BEANS 7. public interface MessageListener { public void onMessage(Message message). It is up to the developer to cast the message to the appropriate type before using it. System. System.4 Receiving a JMS Message While sending a message is a fairly easy process.getString("message"). String name = mapMsg. receiving message is a bit more difficult. } } In this instance the listener knows that the incoming message is a text message.getText()).out. public class FoobieListener implements MessageListener { public void onMessage(Message message) { TextMessage txtMsg = (TextMessage)message.println("Message from " + name + " for you sir: " + msg).3. The example listener below prints to the console the incoming text message. } The interface defines only one simple method for receiving messages. The MessageListener interface defines the functionality an object must be responsible for when handling incoming messages. A message listener is used facilitate the process of receiving incoming messages.

Topic topic = (Topic)jndiContext. TopicSession session = connection. subscriber.lookup("TopicConnectionFactory").3. 0). TopicSubsciber subscriber = session.lookup("topic/FoobieTopic").createTopicSession(false. connection.5 Using Listeners Once a listener is defined.start(). Context jndiContext = new InitialContext(). the JMS connection must be placed into a wait state for incoming messages. The code below shows how to associate a listener with a subscriber and turn on the connection. the subscriber is notified and the listener is called to process the message. Once the message is processed the subscriber goes back into a wait state until the next message is received. // create FoobieListener listener = new FoobieListener(). After the listener is connected to the receiving mechanism. Page 199 c 2010 n + 1. TopicConnectionFactory connectionFactory = (TopicConnectionFactory) jndiCntext.createSubscriber(topic). it can be associated with a topic subscriber or a queue receiver.Java EE Foundations 7. Inc All Rights Reserved . TopicConnection connection = connectionFactory. This is accomplished by calling the start() method on the connection.setMessageListener(listener).createTopicConnection(). // starts listening for incoming messages When a new message comes into the FoobieTopic.

Is there a simpler way to do this? Can’t the J2EE container help with this process? The answer to both question is yes. Page 200 c 2010 n + 1. Inc All Rights Reserved .CHAPTER 7. each listener must be in its own thread of execution. The message driven EJB was created to help in the consumption of JMS messages. JMS AND MESSAGE DRIVEN BEANS Downside To Listeners Since the subscriber is in a constant wait state until a message is received. Thus a different application is necessary for each listener or a single multi-threaded application that spins off each listener into its own thread of execution. Both implementations bring their own levels of complexity.

Inc All Rights Reserved .Java EE Foundations 7. Unlike stateless session beans. If multiple beans are subscribers to the same topic each subscriber will be executed simultaneously. Since the Message driven bean is stateless it can process messages concurrently. In addition. Since a message driven beans sole purpose is processing JMS messages they are by nature stateless. They can only be used to process JMS messages. they can not be accessed through the JDNI and sent Java RMI method calls.4 Message Driven Beans Message driven beans are EJBs that are used to processing incoming JMS messages. They also exist within the J2EE container meaning they are transaction aware. Page 201 c 2010 n + 1. Message driven beans can only be associated with a single Topic or Queue.

The example below transforms the FoobieBean class into a message driven bean associated with the topic “topic/FoobieTopic” @MessageDriven(mappedName="topic/FoobieTopic") public class FoobieBean implements MessageListener { public void onMessage(Message message) { if ( message instanceof TextMessage ) { TextMessage txtMsg = (TextMessage)message.out.println("Message from " + name + " for you sir: " + msg). System.getText()). } else if ( message instanceof MapMessage ) { MapMessage mapMsg = (MapMessage)message.4.: } } } The next step is to use the @MessageDriven annotation to tell the J2EE container that the bean is to be deployed as a message driven bean.CHAPTER 7. The value associated with the mappedName is the JNDI lookup for the specific topic or queue.getText()).println("Message for you sir: " + txtMsg.1 Creating Message Driven Beans The first step in creating a message driven bean is to create an object that implements the message driven interface. System.getString("message").getString("message"). public class FoobieBean implements MessageListener { public void onMessage(Message message) { if ( message instanceof TextMessage ) { TextMessage txtMsg = (TextMessage)message.: } } } Page 202 c 2010 n + 1. Inc All Rights Reserved . String msg = mapMsg. String name = mapMsg. JMS AND MESSAGE DRIVEN BEANS 7. The @MessageDriven annotation has an attribute named “mappedName” is used to associate the bean with either a Topic or a Queue.println("Message from " + name + " for you sir: " + msg). Since the consumption of a JMS message is independent of the delivery mechanism of a Queue or Topic the message driven bean can be mapped to either source. } else if ( message instanceof MapMessage ) { MapMessage mapMsg = (MapMessage)message.out.println("Message for you sir: " + txtMsg.out.out. System. System.getString("name"). String msg = mapMsg.getString("name"). String name = mapMsg.

It will be invoked any time a messages is sent to the FoobieTopic.Java EE Foundations Once the message driven bean is deployed. it is set up as a subscriber to the topic/FoobieTopic and waits to handle incoming JMS messages. Page 203 c 2010 n + 1. Inc All Rights Reserved .

<target name="package-ejb" depends="build"> <jar jarfile=".4. <target name="package-ejb" depends="build"> <jar jarfile="./dist/acme-ejb. They need to be included within the EJB jar file that is deployed to the server./dist/acme-ejb. Below is the ANT jar creation statement used for session beans. Inc All Rights Reserved .jar"> <fileset dir=". The following example assumes that the message driven beans are in the message package.CHAPTER 7.2 Deploying A Message Driven Bean Message driven beans should be treated the same as the session beans./build"> <include name="**/beans/**"/> <include name="**/services/**"/> </fileset> </jar> </target> Session beans need to include the interface along with the bean implementations within the ejb jar file.jar"> <fileset dir=". JMS AND MESSAGE DRIVEN BEANS 7./build"> <include name="**/beans/**"/> <include name="**/services/**"/> <include name="**/message/**"/> </fileset> </jar> </target> Page 204 c 2010 n + 1. The message driven bean code should just be added to the above target.

createTopicConnection().4. Topic. QueueConnectionFactory. // bean logic here } Once the objects are mapped to the JNDI server. the developer has an annotation available to simplify the process. text. Page 205 c 2010 n + 1. @Stateless public class MyBean implements MyLocal { @Resource(mappedName="TopicConnectionFactory") private TopicConnectionFactory factory. @Resource(mappedName="topic/FoobieTopic") private Topic topic. @Stateless public class MyBean implements MyLocal { @Resource(mappedName="TopicConnectionFactory") private TopicConnectionFactory factory. the sending code is the same as sending any other JMS message.3 Messaging MDB From Session Bean When sending a JMS message to a message driven bean from within a session bean. TextMessage text = session. publisher.createTextMessage(). Inc All Rights Reserved . public void sendMessage(String message) { TopicConnection conn = factory. connection. Thus the TopicConnectionFactory.createPublisher(topic). 0).Java EE Foundations 7.publish(text). The @Resource annotation can be used to map an object to and entity located within the JNDI server. The mappedName attribute of the annotation provides the container with the JNDI lookup path. they can be used like any other object within the session bean. and Queue can all be defined as private member attributes using the @Resource annotation. Other than defining the resources. The concept is similar to defining the EntityManager to retrieve entities from within a session bean. } } The @Resource annotation will work just as well with the QueueConnectionFactory and Queues.setText(message). @Resource(mappedName="topic/FoobieTopic") private Topic topic. TopicSession session = conn.createTopicSession(false.close(). TopicPublisher publisher = session.

Inc All Rights Reserved . JMS AND MESSAGE DRIVEN BEANS Page 206 c 2010 n + 1.CHAPTER 7.

Chapter 8 JavaMail Objectives • 207 .

MailService" name="jboss:service=Mail"> <attribute name="JNDIName">java:/Mail</attribute> <attribute name="User">nobody</attribute> <attribute name="Password">password</attribute> <attribute name="Configuration"> <configuration> <property name="mail. Since the API follows RFC standards it is vendor neutral and behaves in a similar fashion to JDCB and JMS APIs. Below is an example of the JBoss configuration file.store.from" value="foo@nplus1. Inc All Rights Reserved .debug" value="false"/> </configuration> </attribute> <depends>jboss:service=Naming</depends> </mbean> </server> The API is meant to provide all mail functionality including sending.user" value="nobody"/> <property name="mail.host" value="mail.protocol" value="pop3"/> <property name="mail.1 JavaMail API The JavaMail API was designed for sending and receiving electronic mail. POP.nplus1.nplus1.0" encoding="UTF-8"?> <server> <mbean code="org.port" value="25"/> <property name="mail.net"/> <property name="mail.jboss. JAVAMAIL 8.host" value="mail.smtp.transport.mail. Each J2EE vendor is responsible for providing an implementation of the API.CHAPTER 8. <?xml version="1. The mail settings are configured differently for each J2EE vendor.pop3. Thus the configurations are platform specific.net"/> <property name="mail. This module will focus only on the delivery of mail and not on reading a current mail store.net"/> <property name="mail. and IMAP.protocol" value="smtp"/> <property name="mail. Page 208 c 2010 n + 1.smtp.

mail.1.Session interface using Java RMI-IIOP.rmi.narrow(reference.class).mail.1 Mail Session The primary entity in working with mail is the javax. For example.lookup("java:/Mail"). The following sections show how to use the Session object to send an email message. the JBoss the default mail entity is found at the JNDI location “java:/Mail”. Session mail = (Session)PortableRemoteObject.Java EE Foundations 8.Session interface. As previously noted.PortableRemoteObject’s static method narrow() must be used to perform the casting necessary to gain access to the session. Object reference = context. it does not provide a mechanism for casting an object. Page 209 c 2010 n + 1. Inc All Rights Reserved . As such. The JNDI session references the javax. Therefore the javax. Once the session with a mail server is obtained. The Session interface is available from the JNDI server. CORBA is platform independent. Session. It is accessed based upon name specified in the vendor specific mail configuration. it is now possible to interact with the mail server.

mail.net"). the constructor must be included within a try/catch block. InternetAddress addr = new InternetAddress("beth@nplus1.2 Email Addresses RFC822 defines the proper format for an email address. The object’s constructor parses the address to ensure RFC compliance. As with Strings. Since this is a checked exception. it will throw an AddressException if any of the addresses are not a valid email address.CHAPTER 8. } catch (AddressException e) { // handle the exception } The InternetAddress object is how email addresses are handled within the JavaMail API.net beth.InternetAddress object. Inc All Rights Reserved . JAVAMAIL 8. It takes as an argument a String with a comma separated list of email address to parse and create. janed@nplus1. try { InternetAddress [] mailAddresses = InternetAddress.net. The method returns an array of InternetAddress objects. If the name is invalid then an AddressException is issued. Page 210 c 2010 n + 1.parse( "beths@nplus1. A typical email address has two parts.1. Once the address is defined it can’t be modified.net"). sarahx@nplus1.internet. beths@nplus1. the only way to define the email address is to pass it into the constructor at object creation. A name followed and a domain name separated by an ampersand. InternetAddresses like Strings are immutable objects.net").net.smith@nplus1. } catch (AddressException e) { // handle the exception } The InternetAddress object provides a static convenience method parse() which allow the creation of multiple email addresses at one time.net The J2EE standard enforces these rules through the javax. try { InternetAddress addr = new InternetAddress("beths@nplus1. Like the constructor.

smith@nplus1.setSentDate(new java. MimeMessage message = new MimeMessage(mail). MimeMessage message = new MimeMessage(mail). the date the message is sent. Session.lookup("java:/Mail"). javax.3 MIME Email Messages Email sent over the Internet is MIME encoded as defined in RFC822. all email addresses must use the InternetAddress object. Object reference = context. As a reminder.setFrom(new InternetAddress("beth. Inc All Rights Reserved . the recipient address(s). Session mail = (Session)PortableRemoteObject.Date()). Notice that an InternetAddress was necessary for the setting of the FROM line of the email message.narrow(reference.net"). Session mail = (Session)PortableRemoteObject.narrow(reference. message. and the body of the message. Once the message is created it is possible to specify the message attributes.lookup("java:/Mail"). Session. Because early Internet was based upon transferring ASCII data.1.Java EE Foundations 8. MIME encoding was created to allow the conversion of binary data into ASCII data. the message subject. Page 211 c 2010 n + 1. message. To instantiate a MimeMessage the developer must have a reference to the mail session and use it to construct the message. the message subject and the date the message was sent.mail.setSubject("This is a test message").class). message.MimeMessage object represents a MIME encoded email message. Object reference = context. The following example shows how to set the FROM address. These include the from address.util.class). The MimeMessage has all of the attributes defined within the EMail specification for a MIME message.

there are different types of recipients a person can specify. Inc All Rights Reserved . It was designed to specify additional people other than the primary person to receive the email message.TO • Message. The values can be any of the following types. The specification provides two other type of recipients. janed@nplus1. InternetAddress [] copy = InternetAddress. InternetAddress address) addRecipients(RecipientType recipientType. The second type is the blind carbon copy or BCC.RecipientType. InternetAddress [] address) The RecipientType is defined within the enumeration of Message.RecipientType.CC.net"). message.RecipientType. message. InternetAddress [] address) addRecipients(RecipientType recipientType. • Message. If additional recipients are required then the addRecipients() method should be used.1.addRecipients(Message. The carbon copy or CC field is used to specify people who are supposed to be copied in on the email message. The setRecipients() method is used to specify the first recipient.RecipientType.BCC Below is an example of setting multiple recipients for all three recipient types. String address) addRecipients(RecipientType recipientType. String address) setRecipients(RecipientType recipientType. copy).net"). This person is the primary receiver for the mail message. to).BCC.RecipientType. JAVAMAIL 8. The most basic is the TO recipient.parse("johnd@nplus1.addRecipients(Message. InternetAddress to = new InternetAddress("sarahx@nplus1.TO.net.setRecipients(Message. The setRecipients() and addRecipients() methods both take the same form.CHAPTER 8.CC • Message.4 Message Recipients Recipients of email messages are assigned using the setRecipients() and addRecipients() methods on the MimeMessage object.net").RecipientType. When sending an email message. InternetAddress address) setRecipients(RecipientType recipientType. Page 212 c 2010 n + 1. It is designed to copy a person in on the email message without any of the other recipients knowing that blind carbon copied person is receiving the message. setRecipients(RecipientType recipientType.RecipientType. "ceo@nplus1. message.

Setting text within the MIME part is simple. An example is a simple text email message with an attachment.addBodyPart(textMessage). the message is ready for delivery. The Multipart interface is used to manage these various segments that can be added to the mail message.1. Inc All Rights Reserved . Once the content is set.setText("This is the content of the email message"). Multipart partManager = new MimeMultipart(). MimeBodyPart textMessage = new MimeMultipart().Java EE Foundations 8. The multipart instance manages a set of body parts. The mimePart is then added to the Multipart to create the email message’s body. It has a setText() method for defining the text of the body part.setText("This is the content of the email message").setText("This is the content of the email message"). partManager. mimePart. message.addBodyPart(textMessage). The body of the email message can contain multiple parts. Page 213 c 2010 n + 1.5 Message Content Once the fields of an email message are filled. The text is one part of the body while the attachment is a second part of the body.setContent(partManager). The concrete implementation of the Multipart interface is the MimeMultipart object. Each body part is defined with the MimeBodyPart object. Multipart partManager = new MimeMultipart(). MimeBodyPart mimePart = new MimeMultipart(). the Multipart is then added to the message as the message’s content. Once the body is assembled. textMessage. MimeBodyPart textMessage = new MimeMultipart(). Multipart partManager = new MimeMultipart(). MimeBodyPart mimePart = new MimeMultipart(). partManager. it is time to turn attention to the body or message content. textMessage.

setFrom(new InternetAddress("beth.net"). It has a static send() method that sends it to the SMTP server for delivery. // create mail message MimeMessage message = new MimeMessage(mail).class).BCC.CHAPTER 8. Session mail = (Session)PortableRemoteObject. "sarahx@nplus1.setText("This is the content of the email message").net.addBodyPart(textMessage).util. MimeBodyPart textMessage = new MimeMultipart().net"). textMessage. message. message.addRecipients(Message. janed@nplus1.net").setSentDate(new java. // obtain mail session from JNDI server Object reference = context. The example below assembles all of the pieces and sends out a simple text email message from beth. and content. message.parse("johnd@nplus1.Date()). // set destination mail list InternetAddress [] to = InternetAddress. JAVAMAIL 8. Transport.setSubject("This is a test message").net was blind carbon copied on the test message.net. Inc All Rights Reserved .net to johnd@nplus1. message. // send message Transport. a destination. The next step is to deliver the message.send(message). The Transport uses the mail session obtained to determine which SMTP server to use.send(message).1.smith@nplus1. Session.smith@nplus1. // add message content Multipart partManager = new MimeMultipart(). partManager.setContent(partManager). message.6 Sending Messages The message has been assembled with a sender. sarahx@nplus1. to). message.TO. a subject.net and janed@nplus1.narrow(reference.RecipientType. The Transport object is responsible for delivering the message.RecipientType. Page 214 c 2010 n + 1.lookup("java:/Mail").setRecipients(Message.

After specifying the attachment information. Additional MimeBodyParts can be added to the Multipart to handle these attachments. The javax. DataHandler handler = new DataHandler(source).setFileName("the-data. The DataHandler provides a common mechanism for accessing data from many different sources.activation. Once the DataSource is obtained.FileDataSource is a concrete implementation of the interface and is used to reference a file on the system. DataSource source = new FileDataSource("/tmp/data. the activation framework must be invoked to handle the file. In addition a file name can be specified for the resource. It is used by the JavaMail API to convert and send the body part. MimeBodyPart attachment = new MimeBodyPart().pdf").7 Attachments Besides sending a simple text message. DataSource fileSource = new FileDataSource("/tmp/data. The Java activation framework is used to manage MIME data that isn’t simple ASCII text data.setDataHandler(handler). The javax. it needs to be added to a DataHandler before being added to the MultiPart message. it is very useful for a developer to be able to send file attachments with the message.DataSource interface is used to provide an abstraction for a collection of data. Inc All Rights Reserved .1.pdf"). The file name of the resource must be passed into the FileDataSource at instantiation. DataHandler handler = new DataHandler(source). attachment. Since a file attachment can be of any data type. Its role is to convert data into the proper MIME encoded data for sending as an email message. MimeBodyPart attachment = new MimeBodyPart().activation. partManager. The DataSource is passed to the handler at construction. DataHandler handler = new DataHandler(source).pdf"). The first step is to get a reference to the file on the system. attachment.setDataHandler(handler). Page 215 c 2010 n + 1.pdf").Java EE Foundations 8. Once the handler is defined it can be added to a MimeBodyPart. the attachment can be added to the Multipart for sending by the transport. DataSource source = new FileDataSource("/tmp/data. DataSource source = new FileDataSource("/tmp/data.pdf").addBodyPart(attachment). attachment.

JAVAMAIL Note that the specified file name doesn’t have to be the same name as the file being attached. // add message content Multipart partManager = new MimeMultipart(). // add content to message message. One final note about the JavaMail API.setRecipients(Message.narrow(reference.setSubject("This is a test message"). attachment.send(message). Session mail = (Session)PortableRemoteObject. message.net").CHAPTER 8.lookup("java:/Mail").RecipientType. MimeBodyPart attachment = new MimeBodyPart().class).RecipientType.txt").addBodyPart(attachment). "sarahx@nplus1.Date()). partManager.TO.net"). Session.setDataHandler(handler). Page 216 c 2010 n + 1. DataHandler handler = new DataHandler(source).setFrom(new InternetAddress("beth. // add attachment DataSource source = new FileDataSource("/tmp/data. message.setContent(partManager). // add text message MimeBodyPart textMessage = new MimeMultipart(). janed@nplus1. message.setSentDate(new java. Below is a complete example of sending a test message with an attachment.net"). // set destination mail list InternetAddress [] to = InternetAddress. message. // create mail message MimeMessage message = new MimeMessage(mail). The methods outline here can be invoked within any session or message driven bean.addBodyPart(textMessage).util.setText("See the attached data file for process results"). The focus of this module has been on the sending of email messages because it can be a vital need when handling business transactions.addRecipients(Message.txt").parse("johnd@nplus1.BCC. to). // send message Transport.setFileName("the-data.net. partManager. Inc All Rights Reserved . message. attachment.smith@nplus1. textMessage. // obtain mail session from JNDI server Object reference = context.

Appendices 217 .

.

2008 Free Software Foundation. Secondarily. this License preserves for the author and publisher a way to get credit for their work. A “Modified Version” of the Document means any work containing the Document or a portion of it. 2001. Inc. <http://fsf. 2007. below. You accept the license if you copy. Such a notice grants a world-wide. which means that derivative works of the document must themselves be free in the same sense.org/> Everyone is permitted to copy and distribute verbatim copies of this license document. to use that work under the conditions stated herein. either commercially or noncommercially. unlimited in duration. Inc All Rights Reserved . APPLICABILITY AND DEFINITIONS This License applies to any manual or other work. while not being considered responsible for modifications made by others. textbook. regardless of subject matter or whether it is published as a printed book.3. with or without modifying it. or with modifications and/or translated into another language. modify or distribute the work in a way requiring permission under copyright law. because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. 2002. 3 November 2008 Copyright c 2000. it can be used for any textual work. But this License is not limited to software manuals. and is addressed as “you”. but changing it is not allowed. A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall Page 219 c 2010 n + 1. We have designed this License in order to use it for manuals for free software. We recommend this License principally for works whose purpose is instruction or reference. or other functional and useful document “free” in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it. It complements the GNU General Public License. Preamble The purpose of this License is to make a manual. that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. 1. The “Document”. refers to any such manual or work. in any medium. which is a copyleft license designed for free software. Any member of the public is a licensee. royalty-free license. either copied verbatim.JAVA EE Foundations A GNU Free Documentation License Version 1. This License is a kind of “copyleft”.

ethical or political position regarding them. as being those of Invariant Sections. A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. Inc All Rights Reserved . a Secondary Section may not explain any mathematics. but only as regards disclaiming warranties: any other implication that these Warranty Page 220 c 2010 n + 1. The “Title Page” means. philosophical. PostScript or PDF designed for human modification. that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor. plus such following pages as are needed to hold. SGML or XML for which the DTD and/or processing tools are not generally available. The “Cover Texts” are certain short passages of text that are listed. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. For works in formats which do not have any title page as such.) The relationship could be a matter of historical connection with the subject or with related matters. Examples of suitable formats for Transparent copies include plain ASCII without markup. (Here XYZ stands for a specific section name mentioned below. the title page itself. commercial. SGML or XML using a publicly available DTD. A copy made in an otherwise Transparent file format whose markup. legibly. “Endorsements”. represented in a format whose specification is available to the general public. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors. in the notice that says that the Document is released under this License. the material this License requires to appear in the title page. A “Transparent” copy of the Document means a machine-readable copy. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. The Document may contain zero Invariant Sections. and a Back-Cover Text may be at most 25 words. The “publisher” means any person or entity that distributes copies of the Document to the public. such as “Acknowledgements”. PostScript or PDF produced by some word processors for output purposes only. preceding the beginning of the body of the text. for a printed book. “Dedications”. A copy that is not “Transparent” is called “Opaque”. The “Invariant Sections” are certain Secondary Sections whose titles are designated. as Front-Cover Texts or BackCover Texts. and the machine-generated HTML. if the Document is in part a textbook of mathematics. If the Document does not identify any Invariant Sections then there are none. (Thus. or of legal. “Title Page” means the text near the most prominent appearance of the work’s title. These Warranty Disclaimers are considered to be included by reference in this License. has been arranged to thwart or discourage subsequent modification by readers is not Transparent. Examples of transparent image formats include PNG. and standardconforming simple HTML. A Front-Cover Text may be at most 5 words. LaTeX input format. Texinfo input format. or “History”. or absence of markup. and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. in the notice that says that the Document is released under this License.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition. An image format is not Transparent if used for any substantial amount of text. XCF and JPG.APPENDIX subject.

Copying with changes limited to the covers. If you publish or distribute Opaque copies of the Document numbering more than 100. all these Cover Texts: Front-Cover Texts on the front cover. and that you add no other conditions whatsoever to those of this License. to give them a chance to provide you with an updated version of the Document. The front cover must present the full title with all words of the title equally prominent and visible. and Back-Cover Texts on the back cover. If you distribute a large enough number of copies you must also follow the conditions in section 3. 4. with Page 221 c 2010 n + 1. provided that you release the Modified Version under precisely this License. You may also lend copies. either commercially or noncommercially. 3. numbering more than 100. However. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document. that you contact the authors of the Document well before redistributing any large number of copies. and the license notice saying this License applies to the Document are reproduced in all copies. but not required.JAVA EE Foundations Disclaimers may have is void and has no effect on the meaning of this License. you may accept compensation in exchange for copies. free of added material. and continue the rest onto adjacent pages. provided that this License. You may add other material on the covers in addition. when you begin distribution of Opaque copies in quantity. you must enclose the copies in covers that carry. 2. VERBATIM COPYING You may copy and distribute the Document in any medium. If you use the latter option. you must either include a machine-readable Transparent copy along with each Opaque copy. clearly and legibly. can be treated as verbatim copying in other respects. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document. as long as they preserve the title of the Document and satisfy these conditions. you must take reasonably prudent steps. and the Document’s license notice requires Cover Texts. and you may publicly display copies. under the same conditions stated above. Both covers must also clearly and legibly identify you as the publisher of these copies. the copyright notices. to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. Inc All Rights Reserved . It is requested. If the required texts for either cover are too voluminous to fit legibly. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above. you should put the first ones listed (as many as fit reasonably) on the actual cover.

year. Include an unaltered copy of this License. Preserve all the copyright notices of the Document. E. You may use the same title as a previous version if the original publisher of that version gives permission. In addition. one or more persons or entities responsible for authorship of the modifications in the Modified Version. Section numbers or the equivalent are not considered part of the section titles. and publisher of the Document as given on its Title Page. you must do these things in the Modified Version: A. Preserve all the Invariant Sections of the Document. H. Page 222 c 2010 n + 1. and from those of previous versions (which should. authors. be listed in the History section of the Document). unaltered in their text and in their titles. if there were any. F. if any. K. or if the original publisher of the version it refers to gives permission. immediately after the copyright notices. unless they release you from this requirement. I. Preserve the section Entitled “History”. a license notice giving the public permission to use the Modified Version under the terms of this License. given in the Document for public access to a Transparent copy of the Document. if it has fewer than five). Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. If there is no section Entitled “History” in the Document. Inc All Rights Reserved . J. as the publisher. Such a section may not be included in the Modified Version. L. M. Include. G. in the form shown in the Addendum below. thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. State on the Title page the name of the publisher of the Modified Version. Preserve its Title. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice. Preserve the network location.APPENDIX the Modified Version filling the role of the Document. together with at least five of the principal authors of the Document (all of its principal authors. and publisher of the Modified Version as given on the Title Page. These may be placed in the “History” section. Use in the Title Page (and on the covers. and add to it an item stating at least the title. You may omit a network location for a work that was published at least four years before the Document itself. new authors. List on the Title Page. Delete any section Entitled “Endorsements”. Preserve the Title of the section. then add an item describing the Modified Version as stated in the previous sentence. and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. For any section Entitled “Acknowledgements” or “Dedications”. create one stating the title. D. B. if any) a title distinct from that of the Document. and likewise the network locations given in the Document for previous versions it was based on. C. as authors. year.

the name of the original author or publisher of that section if known. you must combine any sections Entitled “History” in the various original documents. You may add a passage of up to five words as a Front-Cover Text. O. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. forming one section Entitled “History”. Inc All Rights Reserved . To do this. unmodified. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. to the end of the list of Cover Texts in the Modified Version. but you may replace the old one. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section. In the combination. under the terms defined in section 4 above for modified versions. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document. add their titles to the list of Invariant Sections in the Modified Version’s license notice. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. and any sections Entitled “Dedications”. make the title of each such section unique by adding at the end of it. and a passage of up to 25 words as a Back-Cover Text. and list them all as Invariant Sections of your combined work in its license notice. If there are multiple Invariant Sections with the same name but different contents. you may not add another. COMBINING DOCUMENTS You may combine the Document with other documents released under this License. provided it contains nothing but endorsements of your Modified Version by various parties—for example. 5. and that you preserve all their Warranty Disclaimers. You may add a section Entitled “Endorsements”. These titles must be distinct from any other section titles. you may at your option designate some or all of these sections as invariant. If the Document already includes a cover text for the same cover. COLLECTIONS OF DOCUMENTS Page 223 c 2010 n + 1. 6. and multiple identical Invariant Sections may be replaced with a single copy. in parentheses. statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.JAVA EE Foundations N. or else a unique number. likewise combine any sections Entitled “Acknowledgements”. You must delete all sections Entitled “Endorsements”. on explicit permission from the previous publisher that added the old one. provided that you include in the combination all of the Invariant Sections of all of the original documents. previously added by you or by arrangement made by the same entity you are acting on behalf of. The combined work need only contain one copy of this License.

the original version will prevail. You may include a translation of this License. TRANSLATION Translation is considered a kind of modification. You may extract a single document from such a collection. When the Document is included in an aggregate. or distribute the Document except as expressly provided under this License. 7. modify. in or on a volume of a storage or distribution medium. “Dedications”. and all the license notices in the Document. is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit.APPENDIX You may make a collection consisting of the Document and other documents released under this License. the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate. and replace the individual copies of this License in the various documents with a single copy that is included in the collection. and will automatically terminate your rights under this License. then if the Document is less than one half of the entire aggregate. 9. Inc All Rights Reserved . If the Cover Text requirement of section 3 is applicable to these copies of the Document. provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. so you may distribute translations of the Document under the terms of section 4. and follow this License in all other respects regarding verbatim copying of that document. or “History”. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works. and any Warranty Disclaimers. provided that you also include the original English version of this License and the original versions of those notices and disclaimers. TERMINATION You may not copy. Any attempt otherwise to copy. provided you insert a copy of this License into the extracted document. Page 224 c 2010 n + 1. but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. sublicense. and distribute it individually under this License. this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. sublicense. or distribute it is void. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer. or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. Replacing Invariant Sections with translations requires special permission from their copyright holders. modify. 8. If a section in the Document is Entitled “Acknowledgements”. the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

JAVA EE Foundations However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.

10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document.

11. RELICENSING
“Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site. “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. “Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document. Page 225 c 2010 n + 1, Inc All Rights Reserved

APPENDIX An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.

ADDENDUM: How to use this License for your documents
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

Copyright c YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”.

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with . . . Texts.” line with this:

with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.

If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.

Page 226

c 2010 n + 1, Inc All Rights Reserved

Index
annotations, 23 associating with class, 25 Column, 59 creating, 24 default value, 29 Entity, 59 GeneratedValue, 64 Id, 59 Local, 37, 39 MessageDriven, 202 multiple value, 27 PostActivate, 50 PostConstruct, 49, 50 PreDestroy, 49, 50 PrePassivate, 50 Remote, 37, 39 Remove, 50 Resource, 205 SequenceGenerator, 64 Table, 59 Temporal, 66 TransactionAttribute, 170 Transient, 68 ant, 40, 41, 44, 85 application.xml, 42 CORBA, 47 DataHandler, 215 DataSource, 83 database configuration, 83 persistence units, 84 ear file, 41, 44 EJB, 19 EJBQL, 141 aggregates, 159 and, 151 avg, 159 comparison symbols, 150 count, 159 date types, 149 dynamic values, 148 in, 156 IS EMPTY, 156 IS NULL, 156 like, 153 logical operators, 151 max, 159 min, 159 not, 151 or, 151 ordering results, 157 select, 141 sum, 159 where, 147 email addresses, 210 email configuration, 208 Entity Bean, 19, 54, 57 Cascade, 125 creating, 59 FetchType, 123 generating database keys, 64 JoinColumn, 98, 103, 118 JoinTable, 118 ManyToMany, 115 ManyToOne, 105 mapping to database, 60 OneToMany, 101, 111 OneToOne, 94 OneToOne bidirectional, 96 OrderedBy, 121 relationships, 90 EntityManager, 58 createQuery, 71, 81 find, 71, 78 flush, 71 merge, 80 methods, 71 227

INDEX obtaining, 70 persist, 71, 77 refresh, 71 remove, 71, 79 updating data, 72 using, 69 InitialContext, 46 InternetAddress, 210 issolation levels, 176 Java Server Pages, 14 JavaMail, 18, 208 attachments, 215 DataHandler, 215 email addresses, 210 message content, 213 message receipients, 212 MIME messages, 211 MimeBodyPart, 213, 215 Multipart, 213 sending messages, 214 Session, 209 JDBC, 16 JMS, 21, 180 ByteMessage, 194 listeners, 199, 200 MapMessage, 194, 195 Message interface, 193 message types, 194 messages, 192 ObjectMessage, 194, 195 point to point, 182 properties, 193 publish/subscribe, 181 Queue methods, 190 Queues, 189 receiving message, 198 sending message, 196 StreamMessage, 194 TextMessage, 194 Topic, 184 TopicConnection, 185 TopicPublisher, 187 TopicSession, 186 TopicSubscriber, 188 JNDI, 17, 46 accessing bean, 47 Page 228 InitialContext, 46 JTA, 15, 168 ACID, 15, 169 exceptions, 173 checked, 175 runtime, 174 issolation levels, 176 transaction scopes, 171 Mandatory, 171 Never, 172 Not Supported, 172 Required, 171 Requires New, 171 Supports, 171 TransactionAttribute, 170 mail attachments, 215 mail session, 209 Message Driven Bean, 19, 201 creating, 202 deploying, 204 MessageListener, 202 messaging MDB, 205 MessageListener, 202 MIME encoding, 211 MimeBodyPart, 213, 215 MimeMessage, 211 Multipart, 213 persistence, 161 entity managed, 56 managed, 55 named queries, 163 native queries, 165 paging results, 162 POJO, 38, 58, 60 Query, 139 entity attributes, 144 navigating objects, 143 result list, 142 result methods, 140 types, 139 Queues, 189 methods, 190 relationships considerations, 120 JoinColumn, 98, 103, 118 c 2010 n + 1, Inc All Rights Reserved

37 developing. 94 OneToOne bidirectional. 45 bean instance. 50 PreDestroy. 36 employee manager example. 111 OneToOne. 187 TopicSession. 50 Stateless. 35 temporal. 34 stateless bean life cycle. 101. 50 PostConstruct. 50 Stateful. 186 TopicSubscriber. 105 OneToMany. 184 TopicConnection. 146 Page 229 c 2010 n + 1. 68 Web Services. 19. 39 POJO implementation. 92. 49 stub. 37. 96 Servlets. 14 Session Bean. 22 WSDL. 37. 185 TopicPublisher. 22 XML.JAVA EE Foundations JoinTable. 50 PrePassivate. Inc All Rights Reserved . 22 where. 66 Topic. 36 creating interface. 34. 188 transient. 118 ManyToMany. 35 remote interface. 49. 76 local interface. 40 container management. 49. 38 PostActivate. 39 Remove. 35 accessing. 22 SOAP. 115 ManyToOne. 34 stateful bean life cycle. 36 building ear file. 50 proxy.

Sign up to vote on this title
UsefulNot useful