evaluation copy€¦ · page iv rev 4.1.1 © 2012 itcourseware, llc java enterprise edition...

52
Java Enterprise Edition Student Workbook Evaluation Copy

Upload: others

Post on 29-May-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java EnterpriseEdition

Student Workbook

Evaluation Copy

Page 2: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Page ii Rev 4.1.1 © 2012 ITCourseware, LLC

Java Enterprise Edition

Java Enterprise Edition

Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Authors: Jim Gallentine, John McAlister, Mike Naseef, and Jamie Romero

Editor: Ginny Jaranowski

Special thanks to: Many Java instructors whose ideas and careful review have contributed to the quality ofthis workbook and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2012 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, CO 80112. (303)302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of theirrespective owners.

Evaluation Copy

Page 3: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

© 2012 ITCourseware, LLC Rev 4.1.1 Page iii

Java Enterprise Edition

Contents

Chapter 1 - Course Introduction ............................................................................................................. 9

Course Objectives .......................................................................................................................... 10Course Overview ........................................................................................................................... 12Using the Workbook ...................................................................................................................... 13Suggested References ..................................................................................................................... 14

Chapter 2 - Introduction to Java EE ...................................................................................................... 17

Introduction to Java EE ................................................................................................................... 18Java SE Building Blocks ................................................................................................................. 20Web Applications ........................................................................................................................... 22Web Services ................................................................................................................................. 24Enterprise JavaBeans ...................................................................................................................... 26Additional Java EE APIs ................................................................................................................. 28POJO, Dependency Injection, and Annotations ............................................................................... 30The Java EE Platform ..................................................................................................................... 32

Chapter 3 - Introduction to JSP and JSTL ............................................................................................. 35

MVC and Web Applications ........................................................................................................... 36JSP As the View ............................................................................................................................. 38JSP Scripting Elements .................................................................................................................... 40Request and Response .................................................................................................................... 42Expression Language ...................................................................................................................... 44EL Operators ................................................................................................................................. 46include and forwards ....................................................................................................................... 48JSTL .............................................................................................................................................. 50Conditionals and Iteration in JSTL ................................................................................................... 52JSTL Variables And Output ............................................................................................................. 54Labs ............................................................................................................................................... 56

Chapter 4 - Introduction to Java Servlets and JavaBeans ...................................................................... 59

Java Servlets as the Controller ........................................................................................................ 60HttpServlet ..................................................................................................................................... 62HTTPServletRequest ...................................................................................................................... 64HTTPServletResponse ................................................................................................................... 66

Evaluation Copy

Page 4: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Page iv Rev 4.1.1 © 2012 ITCourseware, LLC

Java Enterprise Edition

HttpSession .................................................................................................................................... 68RequestDispatcher .......................................................................................................................... 70JavaBeans as the Model ................................................................................................................. 72Bean Scopes .................................................................................................................................. 74WAR File ....................................................................................................................................... 76Labs ............................................................................................................................................... 78

Chapter 5 - Introduction to JavaServer Faces ....................................................................................... 81

Frameworks ................................................................................................................................... 82JSF Benefits ................................................................................................................................... 84JSF Tag Libraries ........................................................................................................................... 86Components ................................................................................................................................... 88Managed Beans .............................................................................................................................. 90Event handling ................................................................................................................................ 92Navigation ...................................................................................................................................... 94Validators and Converters ............................................................................................................... 96Lifecycle ......................................................................................................................................... 98JSF Application Structure ............................................................................................................. 100Labs ............................................................................................................................................. 102

Chapter 6 - JMS ................................................................................................................................ 105

Messaging Concepts ..................................................................................................................... 106What is JMS ? .............................................................................................................................. 108Point-to-Point ............................................................................................................................... 110Publish/Subscribe ......................................................................................................................... 112Message Object ........................................................................................................................... 114Session ......................................................................................................................................... 116Creating the Client ........................................................................................................................ 118Labs ............................................................................................................................................. 120

Chapter 7 - EJB3 Overview ............................................................................................................... 123

The Enterprise JavaBean ............................................................................................................... 124EJB Benefits ................................................................................................................................. 126A Simple EJB ............................................................................................................................... 128Local and Remote EJB Access ..................................................................................................... 130Creating a Client ........................................................................................................................... 132Assembly and Deployment of EJBs ............................................................................................... 134Labs ............................................................................................................................................. 136

Evaluation Copy

Page 5: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

© 2012 ITCourseware, LLC Rev 4.1.1 Page v

Java Enterprise Edition

Chapter 8 - Session Beans and Message-Driven Beans ....................................................................... 139

A Session Bean ............................................................................................................................ 140Stateless Session Beans ................................................................................................................ 142PostConstruct and PreDestroy ...................................................................................................... 144Lifecycle of a Stateless Session Bean ............................................................................................ 146Stateful Session Beans .................................................................................................................. 148Lifecycle of a Stateful Session Bean .............................................................................................. 150Lifecycle Callbacks ....................................................................................................................... 152Singleton Session Beans ................................................................................................................ 154Lifecycle of a Singleton Session Bean ............................................................................................ 156Dependency Injection ................................................................................................................... 158Message-Driven Beans ................................................................................................................. 160MDB Lifecycle ............................................................................................................................. 162Sending a Message ....................................................................................................................... 164Labs ............................................................................................................................................. 166

Chapter 9 - Introduction to the Java Persistence API ........................................................................... 169

What is Java Persistence? ............................................................................................................. 170Persistence Objects and Metadata ................................................................................................ 172Creating an Entity Class ................................................................................................................ 174The Persistence Unit ..................................................................................................................... 176The Entity Manager ...................................................................................................................... 178Looking up Entities ....................................................................................................................... 180Deployment .................................................................................................................................. 182Labs ............................................................................................................................................. 184

Chapter 10 - Persisting Entities ........................................................................................................... 187

EntityManager and Persistence Context ......................................................................................... 188Entity Lifecycle ............................................................................................................................. 190Creating and Removing Entities ..................................................................................................... 192Transactions ................................................................................................................................. 194Mapping Entities to Tables ............................................................................................................ 196Primary Keys ............................................................................................................................... 198Entity Relationships ....................................................................................................................... 200Cascading .................................................................................................................................... 202Labs ............................................................................................................................................. 204

Evaluation Copy

Page 6: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Page vi Rev 4.1.1 © 2012 ITCourseware, LLC

Java Enterprise Edition

Chapter 11 - Transactions ................................................................................................................... 207

The Java Transaction API ............................................................................................................. 208The UserTransaction Interface ....................................................................................................... 210Transactions in Java EE................................................................................................................. 212Bean-Managed Transactions ......................................................................................................... 214Container-Managed Transactions .................................................................................................. 216Transaction Attributes ................................................................................................................... 218Transaction Rollbacks ................................................................................................................... 220Labs ............................................................................................................................................. 222

Chapter 12 - Data Binding with JAXB ................................................................................................ 225

W3C XML Schema ..................................................................................................................... 226XML Data Binding Basics ............................................................................................................. 228JAXB Architecture ....................................................................................................................... 230Compiling Schema to Java ............................................................................................................ 232JAXBContext ............................................................................................................................... 234Unmarshalling ............................................................................................................................... 236Marshalling ................................................................................................................................... 238Validation ..................................................................................................................................... 240Custom Binding Declarations ........................................................................................................ 242Labs ............................................................................................................................................. 244

Chapter 13 - Java API for XML-Based Web Services (JAX-WS) ...................................................... 247

JAX-WS ...................................................................................................................................... 248Creating a Web Service Endpoint .................................................................................................. 250The Service Implementation .......................................................................................................... 252The Service Interface .................................................................................................................... 254Generating Artifacts ...................................................................................................................... 256Generated Files ............................................................................................................................ 258Packaging and Deploying the Application ...................................................................................... 260A JAX-WS Client ........................................................................................................................ 262wsimport ...................................................................................................................................... 264Labs ............................................................................................................................................. 266

Chapter 14 - Case Study .................................................................................................................... 269

Case Study Overview ................................................................................................................... 270Persistence ................................................................................................................................... 272

Evaluation Copy

Page 7: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

© 2012 ITCourseware, LLC Rev 4.1.1 Page vii

Java Enterprise Edition

Stateless Session Bean .................................................................................................................. 274Web Tier Client: HTML ................................................................................................................ 276Web Tier Client: Controller Servlet ................................................................................................ 278Web Tier Client: Data Transfer JavaBean ....................................................................................... 280Web Tier Client: JSP ..................................................................................................................... 282Web Tier Client: web.xml .............................................................................................................. 284Message-Driven Bean .................................................................................................................. 286JMS Client ................................................................................................................................... 288JAX-WS Endpoint ....................................................................................................................... 290Web Service Client ....................................................................................................................... 292

Appendix A - Underlying Technologies: RMI and JDBC ...................................................................... 295

RMI ............................................................................................................................................. 296Steps to Create a Remote Object ................................................................................................. 298An RMI Client .............................................................................................................................. 300An RMI Server ............................................................................................................................ 302RMI Utilities ................................................................................................................................. 304The JDBC Connectivity Model ..................................................................................................... 306Connecting to the Database .......................................................................................................... 308Creating a SQL Query .................................................................................................................. 310Getting the Results ........................................................................................................................ 312Updating Database Data ............................................................................................................... 314

Appendix B - JavaMail ....................................................................................................................... 317

Mail Systems and JavaMail ........................................................................................................... 318The javax.mail Packages ............................................................................................................... 320Establishing a Session ................................................................................................................... 322The MimeMessage Class .............................................................................................................. 324Sending a Message ....................................................................................................................... 326Retrieving Email Messages ............................................................................................................ 328Multi-part Messages ..................................................................................................................... 330

Solutions ............................................................................................................................................ 333

Index .................................................................................................................................................. 407

Evaluation Copy

Page 8: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Page viii Rev 4.1.1 © 2012 ITCourseware, LLC

Java Enterprise Edition

Evaluation Copy

Page 9: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Course IntroductionChapter 1

© 2012 ITCourseware, LLC Rev 4.1.1 Page 9

Chapter 1 - Course IntroductionEvaluation Copy

Page 10: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterpise Edition

Page 10 Rev 4.1.1 ©2012 ITCourseware, LLC

Describe the architecture and use of Java EE technologies.

Write web applications that combine Java Servlets, JavaServer Pages, andJavaBeans using the Model-View-Controller architecture.

Develop web applications using the component-based and event-drivenJavaServer Faces framework.

Send and receive asynchronous messages with the Java Message Service.

Describe the Enterprise JavaBean architecture.

Write session and message-driven EJBs.

Access a relational database with the Java Persistence API.

Handle transactions with the Java Transaction API.

Map XML content to domain-specific objects with JAXB.

Integrate legacy systems with JAX-WS web services.

Course Objectives

Evaluation Copy

Page 11: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Course IntroductionChapter 1

© 2012 ITCourseware, LLC Rev 4.1.1 Page 11

Evaluation Copy

Page 12: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterpise Edition

Page 12 Rev 4.1.1 ©2012 ITCourseware, LLC

Audience: Java programmers moving to Java Enterprise Edition.

Prerequisites: Java Programming or equivalent experience.

Classroom Environment:

One Java development environment per student including an ApplicationServer and DBMS Server.

Course Overview

Evaluation Copy

Page 13: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Course IntroductionChapter 1

© 2012 ITCourseware, LLC Rev 4.1.1 Page 13

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Evaluation Copy

Page 14: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterpise Edition

Page 14 Rev 4.1.1 ©2012 ITCourseware, LLC

Basham, Bryan, Kathy Sierra, and Bert Bates. 2008. Head First Servlets and JSP: Passing the SunCertified Web Component Developer Exam (2nd Edition). O'Reilly Media, Sebastopol, CA.ISBN 978-0596516680.

Burke, Bill and Andrew Lee Rubinger. 2010. Enterprise JavaBeans 3.1. O'Reilly Media, Sebastopol,CA. ISBN 978-0596158026.

Geary, David and Cay Horstmann. 2010. Core JavaServer Faces (3rd Edition). Prentice Hall PTR,Upper Saddle River, NJ. ISBN 978-0137012893.

Goncalves, Antonio. 2010. Beginning Java EE 6 with GlassFish 3 (2nd Edition). Apress,Berkeley, CA. ISBN 978-1430228899.

Gupta, Arun. 2012. Java EE 6 Pocket Guide. O'Reilly Media, Sebastopol, CA. ISBN 978-1449336684.

Hall, Marty and Larry Brown. 2003. Core Servlets and JavaServer Pages: Core Technologies, Vol.1 (2nd Edition). Prentice Hall PTR, Uppder Saddle River, NJ. ISBN 978-0130092298.

Hall, Marty, Larry Brown, and Yaakov Chaikin. 2007. Core Servlets and JavaServer Pages:Advanced Technologies, Vol. 2 (2nd Edition). Prentice Hall PTR, Upper Saddle River, NJ.ISBN 978-0131482609.

Heffelfinger, David. 2011. Java EE6 Development with NetBeans 7. Packt Publishing, Birmingham,UK. ISBN 978-1849512701.

Heffelfinger, David. 2010. Java EE 6 with GlassFish 3 Application Server. Packt Publishing,Birmingham, UK. ISBN 978-1849510363.

Keith, Mike and Merrick Schincariol. 2009. Pro JPA2: Mastering the Java Persistence API. Apress,Berkeley, CA. ISBN 978-1430219569.

Schalk, Chris, and Ed Burns. 2009. JavaServer Faces 2.0: The Complete Reference. McGraw-HillOsborne Media, San Francisco, CA. ISBN 978-0071625098.

http://docs.oracle.com/javaee/6/tutorial/doc/

Suggested References

Evaluation Copy

Page 15: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Course IntroductionChapter 1

© 2012 ITCourseware, LLC Rev 4.1.1 Page 15

Evaluation Copy

Page 16: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterpise Edition

Page 16 Rev 4.1.1 ©2012 ITCourseware, LLC

Evaluation Copy

Page 17: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 17

Chapter 2 - Introduction to Java EE

Objectives

Describe the technologies that make upJava EE.

Architect Java EE solutions with varioustypes of external clients.

Define Java EE ease-of-use features,such as POJO, annotations, anddependency injection.

Evaluation Copy

Page 18: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 18 Rev 4.1.1 © 2012 ITCourseware, LLC

The Java Enterprise Edition (Java EE) was designed to make the integration oflarge distributed applications as simple and flexible as possible.

Java EE helps the developer focus on the part of the application that isspecific to the business, instead of on the semantics of making the pieceswork together.

There is a limited set of skills that developers need to learn for their part of theapplication.

Some developers may focus on business logic with EJBs, while othersmay focus on presentation logic in JSF, for example.

The Java EE specification describes the architecture of an application aswell as the specific protocols for communication.

The various developers are guaranteed that their section of theapplication will communicate seamlessly with the others.

The choice of tools and products is also less of a concern, because they alladhere to the same standards.

Introduction to Java EE

Evaluation Copy

Page 19: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 19

Application servers such as Oracle WebLogic, IBM WebSphere, JBoss, and Glassfish implement the JavaEE specification. They provide containers as runtime environments for the various Java EE components. Theweb container hosts JSPs and servlets. The EJB container runs Enterprise JavaBeans within it.

The most common Java EE architecture separates the application into multiple tiers. The Client Tier isusually made up of a browser that is responsible for displaying the user interface on the client's system. TheMiddle Tier can be broken up across the two containers. The web container is responsible for readingHTTP requests and generating HTTP responses. The EJB container holds the business and database accesslogic. The Data Tier contains the database.

You can create Java EE applications that do not make use of the EJB container. These applications typicallyhandle all business and database access logic with servlets or JavaBeans, rather than through EJBs.

You can also create Java EE applications that do not make use of the web container. Clients to theseapplications are typically stand-alone clients, rather than browser-based clients.

Client Tier Middle Tier Data Tier

Application Server

DatabaseWeb Browser Web Container

EJB Container

Evaluation Copy

Page 20: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 20 Rev 4.1.1 © 2012 ITCourseware, LLC

Java SE Building Blocks

The Java Enterprise Edition builds on the Java Standard Edition (Java SE).

Java SE contains the Java Virtual Machine and various tools, such as the javaccompiler.

Java SE also contains many bundled libraries that Java EE applications also use.

Java Database Connectivity (JDBC) allows Java EE applications toconnect to relational databases.

Remote Method Invocation (RMI) is the underlying protocol for remotecommunications to Enterprise JavaBeans (EJB).

RMI/IIOP allows non-Java clients to interact with Java EEapplications.

Java Naming and Directory Interface (JNDI) is used to perform lookupson naming services to find EJBs, among other things.

Java API for XML Processing (JAXP) can be used by Java EEapplications when working with XML content.

Evaluation Copy

Page 21: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 21

Application Server

DatabaseWeb Browser Web Container

EJB Container

RMI/IIOP

HTTP

JDBC

Standalone Client

RMI/IIOP

Evaluation Copy

Page 22: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 22 Rev 4.1.1 © 2012 ITCourseware, LLC

Web Applications

A web application reads HTTP request information from a browser andgenerates a response in HTML.

JavaScript and Cascading Style Sheets (CSS) can also be generated aspart of the response.

The web container hosts web applications.

A container is a runtime environment for Java EE components.The web container hosts JavaServer Pages, Java servlets, and JavaBeans.Alternatively, the web container can host JavaServer Faces applications.

A servlet is a Java program that runs in the web container.

Servlets typically act as controllers, reading request information anddelegating calls to JavaBeans and JSPs to fulfill the client's needs.

JavaBeans are simple Java classes that follow a few coding conventions.

In Java EE, JavaBeans either call Enterprise JavaBeans to perform thebusiness and data access logic, or they do it themselves.

JavaServer Pages (JSP) are HTML documents with embedded JSP tags.

The JSP tags usually access JavaBeans to present the results of thebusiness logic invocation.JSPs are devoted to generating the view back to the browser.

JavaServer Faces (JSF) is a framework that makes developing web applicationseasier through the use of tag libraries and a provided controller servlet.

Web applications are packaged in Web Archive (WAR) files.

Evaluation Copy

Page 23: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 23

Some of the coding conventions for JavaBeans include:

All JavaBeans have get and set methods to expose properties.JavaBeans must have a no-argument constructor.JavaBeans should implement the java.io.Serializable interface.

Application Server

Database

Web BrowserWeb Container

EJB Container

1) HTTP Request

7) HTTP Response

HTM

L

Servlet

2) method()

5) fo

rward

()

6) get

...()

JSP

JavaBean

3) method() 4) JDBC

Evaluation Copy

Page 24: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 24 Rev 4.1.1 © 2012 ITCourseware, LLC

Web Services

A web service reads request information from an XML document and sends backan XML response.

The XML content can be structured as a Simple Object Access Protocol(SOAP) document.

A Web Service Description Language (WSDL) document describes theinterface to the web service.

Java EE provides several APIs to support web service development.

The Java API for XML-based Web Services (JAX-WS) supports bothservlets and EJBs as web service endpoints.

JAX-WS uses WSDL documents to generate client-side helper filesto simplify client development.

On the server side, the WSDL can be automatically generated byJAX-WS.

The Java API for RESTful Web Services (JAX-RS) supportsRepresentational State Transfer (REST) style web services.

REST web services are invoked using standard HTTP methods(GET, PUT, etc.) and return XML results.

Web service clients can be written in any language.

Evaluation Copy

Page 25: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 25

Application Server

DatabaseWeb Container

EJB Container

HTTP

Standalone ClientServlet

web service

endpoint

SOAP

SOAP

Evaluation Copy

Page 26: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 26 Rev 4.1.1 © 2012 ITCourseware, LLC

Enterprise JavaBeans

Enterprise JavaBeans (EJB) contain the business logic for Java EE applications.

There are two types of Enterprise JavaBeans.

Session Beans contain task-oriented business logic.

Message-Driven Beans (MDBs) act as asynchronous message consumers.

EJBs use persistent objects called entities for persisting data to the database.

EJBs and entities run within the EJB container of the application server.

The container handles system-level services for the EJB, allowing thedeveloper to focus on business logic.

Examples of system-level services include transactions, security,and concurrency.

EJBs are packaged in Java Archive (JAR) files.

When the application server also serves as the web container, JAR and WARfiles can be packaged and deployed in an Enterprise Archive (EAR) file.

Evaluation Copy

Page 27: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 27

Application Server

DatabaseWeb Browser

Web ContainerEJB Container

HTTPJDBC

Standalone Client

Session Entity

MDB

RMI/IIO

P

Evaluation Copy

Page 28: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 28 Rev 4.1.1 © 2012 ITCourseware, LLC

Additional Java EE APIs

In addition to JSPs, servlets, and EJBs, Java EE also supports several otherAPIs.

The Java Transaction API (JTA) is used to demarcate transactionalboundaries for Java EE applications.

The JTA integrates Java EE applications with an application server'stransaction manager to allow for distributed transactions.

Java Message Service (JMS) uses Message-Oriented Middleware (MOM)for asynchronous point-to-point or publish/subscribe communication.

Point-to-Point messaging guarantees that a message is delivered toa single receiver.

Publish/Subscribe messaging broadcasts messages to allregistered subscribers.

MDBs are consumers of JMS messages.

JavaMail can be used to create user agents for sending email messages.

JavaMail integrates into existing mail transfer agents, such assendmail or Microsoft Exchange Server.

The Java EE Connector Architecture allows Java EE applications to integratewith existing Enterprise Information Systems (EIS).

EIS examples include applications from SAP, PeopleSoft, and IBM'sCICS, as well as non-Java legacy applications.

Evaluation Copy

Page 29: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 29

Application Server

DatabaseWeb Browser

Web Container

EJB Container

HTTP JDBC

Standalone Client

Session Entity

MDB

Mail Server EIS

Asynchronous

Message Client

MOM

JMS

JMS

JTA

Transaction

Manager

RMI/IIOP

Java

Mai

l

Connec

tor

Note:There are five different types of external Java EE clients.

1. Browser-based clients access web applications over HTTP.

2. Web service clients use XML over the HTTP protocol to access servlet or EJB endpoints.

3. Stand-alone Java clients can use RMI to call EJBs.

4. Non-Java clients can use RMI/IIOP to access EJBs.

5. JMS clients send messages to MOM implementations to be delivered to MDBs.

Evaluation Copy

Page 30: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 30 Rev 4.1.1 © 2012 ITCourseware, LLC

POJO, Dependency Injection, and Annotations

The primary goal of the Java EE 5 and 6 releases was ease of development.

Java EE embraces new and existing ideas to attain this goalincluding POJOs, dependency injection, and annotations.

Use Plain Old Java Objects (POJO) for creating sessionand message-driven beans, as well as for building persistent entities.

As the name implies, a POJO is a simple Java class.

Previous versions of Java EE required EJBs to implement specificinterfaces to conform to the specification.

This made it difficult to extract the EJB from the container fortesting.

Use dependency injection to access resources such as EJBs, JDBCDataSources, and JMS Destinations.

The container will find the resource and inject an instance of it into a fieldfor you.

Before injection was available, you would write several lines of JNDI codeto look up resources.

Java SE 5 introduced annotations to the Java language as a way to addmetadata directly within source code.

Java EE makes heavy use of annotations as an alternative to theverbose XML deployment descriptors used in previous versions.

Evaluation Copy

Page 31: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 31

ShoppingCartBean.java...@Statefulpublic class ShoppingCartBean implements ShoppingCart {

@Resource(mappedName = "jms/MyQueueFactory")private ConnectionFactory connectionFactory;@Resource(mappedName = "jms/MyQueue")private Queue queue;@EJBprivate CreditCardValidator validator;private ShoppingBasket shoppingBasket;

public void addItem(String code, int quantity) {shoppingBasket.addItem(code, quantity);

}...

}

Use the @Stateful annotationto identify this EJB as astateful session bean.

Use the @Resourceannotation to instruct the

container to inject aninstance of the Queue

class into the queue field.

Evaluation Copy

Page 32: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 32 Rev 4.1.1 © 2012 ITCourseware, LLC

The Java EE Platform

Java EE encompasses more than just the application programming model thathas been described.

The Java EE Platform specifies a set of required APIs and policies needed torun Java EE applications.

Any operating system can be used, as long as the Java EE platform isavailable.

The GlassFish Server Open Source Edition serves as the referenceimplementation for Java EE and can be used to develop and deploy your JavaEE applications.

You can instead use other application servers such as Oracle WebLogic,IBM WebSphere, or JBoss.

The Java EE Compatibility Test Suite is a set of tests designed to verify that aproduct is compatible with the Java EE platform standard.

Vendors compete on implementations, rather than on standard APIs.

This ensures application portability.

Evaluation Copy

Page 33: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 2 Introduction to Java EE

© 2012 ITCourseware, LLC Rev 4.1.1 Page 33

Application servers, even the Glassfish Server, have proprietary entries in XMLconfiguration files, calleddeployment descriptors, to define things such as security and database connections. While the code maywork across implementations, adjustments will have to be made to the deployment descriptors that arepackaged with the EAR files

The Glassfish Application Server can be downloaded for free as part of the Java EE SDK from http://www.oracle.com/technetwork/java/javaee/downloads/index.html.

Java EE APIs and Technologies

Web Application Technologies:JavaServletsJSP — JavaServer PagesJSF — JavaServer FacesJSTL — JSP Standard Tag Library

Enterprise Application Technologies:Bean ValidationEJB — Enterprise JavaBeansJCA — Java EE Connector ArchitectureJPA — Java Persistence APIJMS — Java Message ServiceJTA — Java Transaction APIJavaMailWebBeans

Web Service Technologies:JAXB — Java Architecture for XML BindingJAX-WS — Java API for XML-Based Web ServicesJAX-RS — Java API for RESTful Web ServicesJAX-RPC — Java API for XML-Based RPCJAXR — Java API for XML Registries

List of Java SE Supporting APIs and Technologies:JDBC — Java DataBase ConnectivityJAXP — Java API for XML ProcessingJMX — Java Management ExtensionJNDI — Java Naming and Directory InterfaceRMI— Java Remote Method Invocation

Evaluation Copy

Page 34: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 34 Rev 4.1.1 © 2012 ITCourseware, LLC

Evaluation Copy

Page 35: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 169

Chapter 9 - Introduction to the JavaPersistence API

Objectives

Describe the Java Persistence API.

Explain the concepts of entity managersand persistence units.

Create an entity class to represent apersistent object.

Use an entity manager to retrieve an objectfrom a data store.

Deploy a Java EE application that uses apersistence unit.

Evaluation Copy

Page 36: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 170 Rev 4.1.1 © 2012 ITCourseware, LLC

The Java Persistence API is a database persistence mechanism introduced inJava EE 5.

It is designed to simplify the persistence of Plain Old Java Objects(POJO) in relational databases using object-relational mapping.

In EJB 3 it replaces the Entity Beans that were used for persistent objectsin prior EJB releases.

It is also designed to be used with Java SE.

Java Persistence incorporates features from several popular persistence projects,such as Hibernate, TopLink, and JDO, as well as functionality from earlier EJBEntity Beans.

Java Persistence provides flexible object-relational mapping features.

The persistence provider can generate the database schema or thedeveloper can configure the mapping to work with an existing schema

Java Persistence defines a standard object query language that is independent ofthe database or persistence providers.

The classes, interfaces, and annotations that make up the API are located in thejavax.persistence package.

What is Java Persistence?

Evaluation Copy

Page 37: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 171

Evaluation Copy

Page 38: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 172 Rev 4.1.1 © 2012 ITCourseware, LLC

Persistence Objects and Metadata

Developers create POJO objects and persist them using entity managers, whichare transparently managed by a persistence provider.

The application developers have control over the persistence of objectsthrough a simple API.

The persistence provider can optimize database access.

Persistence metadata can be specified using annotations or XML deploymentdescriptors.

The specification defines default values, which are designed to minimizethe amount of metadata needed by most applications.

Metadata defined in deployment descriptors override annotations.

This simplifies development and maintains the flexibility to modifyassembly information at deployment.

Evaluation Copy

Page 39: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 173

Application

Persistence Provider

Entity

ManagersJDBC

API

JDBC Driver

JDBC-Accessible

Database

Evaluation Copy

Page 40: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 174 Rev 4.1.1 © 2012 ITCourseware, LLC

To declare a class as an entity, use the @Entity annotation on the classdeclaration.

An entity class must have a public or protected no-argument constructor, mustnot be final, and may not have final methods

Instance variables must not be public or final.

You must annotate the primary key field using @Id annotation on thecorresponding field or property get method.

The persistence provider accesses the object's state using either field-based orproperty-based access.

Indicate the access type via placement of @Id annotation.

Field-based access — Accesses the instance variables directly.

All non-transient fields are persisted.

Property-based access — Accesses properties using get and set methods.

All JavaBean-style properties are persisted.

To prevent a field or property from being persisted, use the @Transientannotation.

The class may contain other business methods, which will be ignored by thepersistence provider.

Creating an Entity Class

Evaluation Copy

Page 41: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 175

This method defines aphoneNumber persistent

property.

This class usesproperty-based access.

The property name isnot the same as thedatabase column.

@Transient notation isnot needed here.

The fullPhone propertyis derived, not stored in

the database.

JPA1-JavaSE/src/emp/Employee.java...@Entitypublic class Employee { ... @Id @Column(name = "empId") public int getId() { return id; }

public void setId(int id) { this.id = id; } ... public String getPhoneNumber() { return phoneNumber; }

public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }

@Transient public String getFullPhone() { return new StringBuilder(areaCode).append("-") .append(phoneNumber).toString(); } ...}

The same entity could be coded as follows using field-based access:JPA1-JavaSE/Employee.alternative.txt...@Entitypublic class Employee { @Id @Column(name="empId") private int id; private String firstName; private String lastName; private String title; private String areaCode; private String phoneNumber;

... public String getFullPhone() {...

Evaluation Copy

Page 42: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 176 Rev 4.1.1 © 2012 ITCourseware, LLC

A persistence unit is a named set of entities managed by an entity managerfactory and the mapping of those entities to the database.

Define persistence units in persistence.xml in the META-INF directory of thepersistence unit root.

Declare the persistence unit name using the name attribute of the<persistence-unit> element.

Specify the entity classes to be managed using the <class> and <jar-file>elements; JAR files will be scanned for annotated classes.

You should always provide the <class> elements for Java SEapplications to ensure portability.

Provide configuration information for the entity managers using the<property> element.

You might use these in a Java SE environment to specify thedatabase configuration.

Specify the JNDI name of the data source using <jta-data-source> or<non-jta-data-source> elements.

Use these in a Java EE environment with container-managed datasources.

Specify object/relational mapping files, if any, using the <mapping-file>element.

You can use XML mapping files rather than annotations to supplymetadata to the persistence provider.

The Persistence Unit

Evaluation Copy

Page 43: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 177

For Java SE, youmust define database

access properties.

This element definesthe JPA-JavaEEpersistence unit.

This data source willbe managed by theJava EE container.

The root of the persistence unit is searched for classes annotated with the @Entity annotation, unless<exclude-unlisted-classes> is specified in persistence.xml.

The set of classes that make up a persistence unit is the union of the classes specified with <class> and<jar-file> elements, annotated classes located in the persistence unit root, and classes referenced in themapping files.

JPA1-JavaSE/src/META-INF/persistence.xml<?xml version="1.0" encoding="UTF-8"?><persistence ...> <persistence-unit name="JPATest"> <class>emp.Employee</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/jee" /> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" /> <property name="javax.persistence.jdbc.user" value="APP" /> <property name="javax.persistence.jdbc.password" value="APP" /> </properties> </persistence-unit></persistence>

JPA1-JavaEE/src/META-INF/persistence.xml<?xml version="1.0" encoding="UTF-8"?><persistence ...> <persistence-unit name="JPA-JavaEE"> <jta-data-source>jdbc/jee</jta-data-source> <class>emp.Employee</class> <properties> <property name="eclipselink.logging.level" value="SEVERE"/> </properties> </persistence-unit></persistence>

Evaluation Copy

Page 44: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 178 Rev 4.1.1 © 2012 ITCourseware, LLC

Use an entity manager to retrieve or store an entity in a database.

In Java SE, you must use an EntityManagerFactory to obtain theEntityManager.

EntityManagerFactory factory=Persistence.createEntityManagerFactory("myPersistUnit");

EntityManager entityMgr = factory.createEntityManager();

Use the Persistence class to get the factory for a persistence unit.

In Java EE, you can use injection to have the Java EE container provide acontainer-managed EntityManager.

Use the @PersistenceContext annotation to specify the persistence unit.

public class MyServlet extends HttpServlet {@PersistenceContext(unitName="myPersistenceUnit")private EntityManager entityMgr;

The container will inject an EntityManager instance to the annotatedfield.

You can only use injection in a container-managed object, such as aservlet, JSF managed bean, or EJB.

Be sure to close an EntityManager that is obtained from anEntityManagerFactory.

Also, close the EntityManagerFactory if you obtained it from thePersistence class.

You must not close container-managed EntityManagers orEntityManagerFactorys.

The Entity Manager

Evaluation Copy

Page 45: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 179

This returns anEntityManagerFactory

for the JPATestpersistence unit.

JPA1-JavaSE/src/emp/EmployeeQuery.javapackage emp;

import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;

public class EmployeeQuery { static int empId = 123443;

public static void main(String[] args) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("JPATest"); EntityManager em = emf.createEntityManager();

Employee employee = em.find(Employee.class, empId);

if (employee != null) { System.out.println(employee); }

em.close(); emf.close(); }}

Try It:The examples in this chapter require a database. Ask you instructor how to start your database server.Then, compile and run EmployeeQuery.java from the JPA1-JavaSE project to see data associated withthe employee whose id is 123443. Finally, run ListEmployees.java to see which employees are in thedatabase and modify EmployeeQuery.java to search for a different employee.

Evaluation Copy

Page 46: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 180 Rev 4.1.1 © 2012 ITCourseware, LLC

Looking up Entities

To load an entity, call the EntityManager.find() method.

Employee employee = entityMgr.find(Employee.class, 123443);

Pass the class type of the entity as the first parameter.

Pass the primary key as the second parameter.

find() returns null if there is no such entity.

Perform queries for entities using the EntityManager.createQuery() method,passing in a Java Persistence API Query Language (JPQL) string.

String sql = "SELECT e FROM Employee e ORDER BY e.id";Query query = entityMgr.createQuery(sql);List emps = query.getResultList();

Call getSingleResult() or getResultList() on the returned Query objectto execute a query that returns a single entity or multiple entities,respectively.

Substitute values for embedded JPQL placeholders with thesetParameter() method.

sql = "SELECT e FROM Employee e WHERE e.id = :theId";query = entityMgr.createQuery(sql);query.setParameter("theId", 123443);Employee emp = (Employee)query.getSingleResult();

Specify named parameters with :name syntax or ordinal parameterswith ?index syntax.

sql = "SELECT e FROM Employee e WHERE e.id = ?1";query = entityMgr.createQuery(sql);query.setParameter(1, 123443);

Evaluation Copy

Page 47: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 181

The primary key of theEmployee entity.

This query returns allEmployee entities, ordered

by the id field.

The containerinjects an

EntityManager inthe em field for the

JPA-JavaEEpersistence unit.

JPA1-JavaEE/src/web/EmployeeQueryServlet.java...@WebServlet("/EmployeeQueryServlet")public class EmployeeQueryServlet extends HttpServlet { @PersistenceContext(unitName = "JPA-JavaEE") private EntityManager em;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { PrintWriter out = res.getWriter(); String idparm = req.getParameter("id"); if (idparm == null || idparm.trim().length() == 0) { listAllEmployees(out); } else { Integer id = new Integer(idparm); showEmployee(out, id); } }

@SuppressWarnings("rawtypes") public void listAllEmployees(PrintWriter out) { Query q = em .createQuery("SELECT e FROM Employee e ORDER BY e.id"); List emps = q.getResultList(); for (Object emp : emps) { out.println(emp); } }

public void showEmployee(PrintWriter out, Integer id) { Employee emp = em.find(Employee.class, id); if (emp != null) { out.println(emp); } else { out.println("no record found for employee id " + id); } }}

Try It:Deploy the web application in the JPA1-JavaEE project to your application server. Navigate to http://localhost:8080/JPA1. Use 123443 for the id of the Employee to query.

Evaluation Copy

Page 48: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 182 Rev 4.1.1 © 2012 ITCourseware, LLC

You must deploy your persistence classes so that they are accessible to both thepersistence manager and the application.

Make sure the classes that make up the persistence unit are accessible viathe application classpath.

You can place them in a location separate from the root of thepersistence unit.

Make sure that the root of the persistence unit is also accessible to thepersistence manager.

For Java SE, the root of the persistence unit may be a JAR file or a directory inthe classpath of the application.

For Java EE, the root of the persistence unit may be one of the following:

1. An EJB-JAR file.

2. The WEB-INF/classes directory of a WAR file.

persistence.xml will be located in WEB-INF/classes/META-INF.

3. A JAR in the WEB-INF/lib directory in a WAR file.

4. A JAR in the lib directory in an EAR file.

5. An application client JAR.

Be sure to declare any data sources that are referenced by your persistence units.

Deployment

Evaluation Copy

Page 49: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 183

Evaluation Copy

Page 50: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 184 Rev 4.1.1 © 2012 ITCourseware, LLC

Create an entity class for the address entity. Make sure your field or property names match thecolumn names in the database. Modify persistence.xml to include your new class.(Solutions: emp/Address.java, META-INF/persistence.xml)

Add a property to the employee entity to hold the addrId column. ModifyEmployeeQuery.java to display the address for the employee.(Solutions: emp/Employee.java, emp/EmployeeQuery1.java)

Create an entity class for the department entity. Modify persistence.xml to include yournew class.(Solutions: emp/Department.java, META-INF/persistence.xml)

Add a property to the employee entity to hold the deptCode column. ModifyEmployeeQuery.java to display the department for the employee.(Solutions: emp/Employee.java, emp/EmployeeQuery2.java)

(Optional) Write a client that looks up employees by last name using the Query interface.(Solution: emp/EmployeeLastNameQuery.java)

Labs

Evaluation Copy

Page 51: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Chapter 9 Introduction to the Java Persistence API

© 2012 ITCourseware, LLC Rev 4.1.1 Page 185

Employee

firstName VARCHAR(20)

lastName VARCHAR(30)

areaCode CHAR(3)

phoneNumber VARCHAR(8)

title VARCHAR(20)

citizen CHAR(1)

deptCode CHAR(2)

addrId INTEGER

Department

code CHAR(2)

name VARCHAR(30)

emp Id INTEGER

Address

id INTEGER

street1 VARCHAR(40)

street2 VARCHAR(40)

city VARCHAR(30)

state CHAR(2)

zip VARCHAR(10)

deptCode=code

addrId=id

Evaluation Copy

Page 52: Evaluation Copy€¦ · Page iv Rev 4.1.1 © 2012 ITCourseware, LLC Java Enterprise Edition HttpSession ..... 68

Java Enterprise Edition

Page 186 Rev 4.1.1 © 2012 ITCourseware, LLC

Evaluation Copy