Building EJB 3

download Building EJB 3

of 65

Transcript of Building EJB 3

  • 8/3/2019 Building EJB 3

    1/65

    Building EJB 3.0 applications with WebSphere Application Server

    Using the WebSphere Application Server V6.1 Feature Pack for EnterpriseJavaBeans 3.0

    Roland Barcia , Senior Technical Staff Member, IBMJeffrey Sampson ( [email protected] ), WebSphere Technical Sales Specialist, IBMSummary: EJB 3.0 is a major step forward in simplifying application development in the enterprise. By using theIBM WebSphere Application Server V6.1 Feature Pack for Enterprise JavaBeans 3.0, you can benefit from thesimplified development experience, new persistence model, and new features such as interceptors, while stilldeploying to a robust WebSphere platform. This content is part of the IBM WebSphere Developer Technical Journal .Tags for this article: 7, ejb , ejb_(enterprise_javabeans)_technology , upgrade , websphere Tag this! Update My dW interests (Log in | What's this? )Skip to help for Update My dW interests

    Date: 12 Dec 2007Level: IntermediateAlso available in: Chinese

    Activity: 35944 viewsComments: 0 ( View | Add comment - Sign in)

    Average rating (28 votes)Rate this article Introduction Enterprise JavaBeans 3.0 is a major enhancement to the EJB specification, introducing a new POJO-basedprogramming model that greatly simplifies development. The EJB 3.0 specification was created under JSR 220, andis divided into three documents:

    y EJB 3.0 Simplified AP I: Defines the new simplified API used to code EJB components; specifically, sessionbeans and message-driven beans.

    y E nterprise J ava B eans Core Contracts and Requirements: Defines the EJB contracts between the beanand the EJB container.

    y

    Persistence API: Defines the new Persistence Model for Java.This article introduces you to the IBM WebSphere Application Server V6.1 Feature Pack for EJB 3.0, and shows you

    how to build a Java Persistence API (JPA) and session bean POJO from scratch, plus how to run it insideWebSphere Application Sever. To highlight aspect oriented programming enhancements to the EJB 3.0 specification,this article will also walk you through building an additional session bean, demonstrating POJO injection, and helpyou build an EJB 3.0 interceptor.This article uses the WebSphere Application Server Toolkit V6.1 and the Dali plug-in available from Eclipse. IBMRational Application Developer V7.5 was released as an open beta bundled with the Eclipse Dali functionality, soyou might want to consider looking into that. You will notice future articles use Rational Application Developer V7.5 tobuild EJB 3.0 applications.Preparation In this article, you will build an EJB 3.0 application within WebSphere Application Server V6.1 using the new FeaturePack for EJB 3.0. For this example, the sample application is a simple customer order system, in which a customer creates an order, adds line items, and then submits the order. Figure 1 illustrates the use cases in this samplesystem, and the sequence in which the use cases are executed is shown in the activity diagram in Figure 2.

    F igure 1. Sample application use cases

  • 8/3/2019 Building EJB 3

    2/65

    F igure 2. Sample application use case sequence

    This article assumes:y WebSphere Application Server V6.1 is installed.y WebSphere Application Server V6.1 Feature Pack for Enterprise JavaBeans 3.0 has been downloaded.y WebSphere Application Server Toolkit v6.1 is installed.y Database schema and test data has been configured. (The DDL for populating a Derby database is provided

    in the download materials for this article.)

  • 8/3/2019 Building EJB 3

    3/65

    Install the feature pack To deploy EJB 3.0 applications inside WebSphere Application Server V6.1, you need to install the EJB 3.0 FeaturePack. This section summarizes highlights of installing the Feature Pack onto an existing WebSphere ApplicationServer V6.1. Be sure to check the Feature Pack Read Me file for other prerequisites. The steps below explain how toinstall the Feature Pack for EJB 3.0 into a simple configuration consisting of a single application server profile. For planning and installation guidance for installing to a Network Deployment configuration, refer to the links on theresults panel of the installation wizard. (For complete installation instructions, see the WebSphere Application Server

    Information Center)1. Locate the EJB3 directory in your feature pack install image. Double-click install.exe to launch the

    installation wizard.2. On the Welcome panel of the installation wizard, verify that you are installing the EJB3 feature pack by

    clicking Next .3. Accept the terms of the licence agreement and click Next .4. A prerequisite check is performed. The feature pack installation image also contains two required fixpacks

    and will prompt you to install them if they are not present. Click Next to continue the installation.5. Use the B rowse button to navigate to the WebSphere Application Server installation directory.6. If the application server is still running you might be presented with the perquisite error message shown in

    Figure 3. If so, go B ack and stop the application server manually. After the application server is stopped,click Next again on the preceding panel to continue.

    F igure 3. Prerequisite E rror

    7. A summary panel will display next, listing the items to be installed (Figure 4). Click Next to install the featurepack.

  • 8/3/2019 Building EJB 3

    4/65

    F igure 4. Installation Summary

    8. When the installation completes, the panel shown in Figure 10 will display. Un-check Launch the Profilemanagement tool and click F inish . (Links with instructions and considerations for installing the featurepack to a Network Deployment topology are also available on this panel.)

    F igure 5. Launch Profile Manager

    Add Dali to the Application Server Toolkit

  • 8/3/2019 Building EJB 3

    5/65

    Dali is a Object/Relational mapping plug-in for Eclipse that provides a Java Persistence perspective that supportstop-down, bottom-up, and meet-in-the-middle O/R mapping. Dali also provides wizards and edit boxes for managingvarious Java Persistence API (JPA) annotations. Dali can be added to either the WebSphere Application Server Toolkit or Rational Application Developer V7.0.x. (Keep in mind that Dali is an open source plug-in so support comesfrom Eclipse. You can also use the Rational Application Developer V7.5 Beta as an alternative, which comes with theDali plug-in installed. See Resources for more.)To add Dali to the Application Server Toolkit:

    1. Download the latest 0.5 version of Dali .2. Make sure that the Application Server Toolkit is stopped.3. Extract the contents of the Dali download file to the main Application Server Toolkit installation directory.

    (This is done because the file contains the directory path starting with the eclipse subdirectory that resides inthe Application Server Toolkit install directory.)

    4. From a command prompt, go to the Application Server Toolkit install directory and use this command to startthe toolkit:ast.exe -clean This command will make sure the Dali plug-in will be detected.

    B ack to top

    A simple example You are now ready to build your first EJB 3.0 application for WebSphere Application Server. By following the steps inthis section, you will develop a simple JPA POJO and a session bean using the example described earlier, and thentest the scenario:

    A. Set up the development environment B. Create your first JPA POJO C. Create a simple sessions bean D. Import the client

    A. Set up the development environment 1. First, you need to create the desired projects:

    a. From the J2EE Perspective in the Application Server Toolkit, right-click within the Project Explorer and select New => E nterprise Application Project (Figure 6).

    F igure 6. New E nterprise Application Project

  • 8/3/2019 Building EJB 3

    6/65

    b. In the New EAR Application Project wizard under the Target Runtime section, click New .c. In the New Server Runtime wizard (Figure 12), select WebSphere Application Server v6.1 and

    click Next .

    F igure 7. WebSphere Application Server v6.1 runtime

    d. Enter the name of the WebSphere Application Server installation directory, if yours is different thanthe default. Click F inish .

    e. Name the project OrderSystem and ensure that the Target Runtime is WebSphere ApplicationServer v6.1 (Figure 8). (Do not select the stub option). Press F inish .

    F igure 8. E AR Application Project Wizard

  • 8/3/2019 Building EJB 3

    7/65

    f. Your EAR file should display an error because there are no Java EE modules. EJB 3.0 is a plain

    POJO model, so you will create a simple Java project as a utility project that will contain your EJB3.0 POJOs.g. Right-click the O rderSystem EAR and select New=> O ther (Figure 9).

    F igure 9. Create new project

  • 8/3/2019 Building EJB 3

    8/65

    h. Expand J 2EE => Utility Project and click Next (Figure 10). A utility project is a plain Java projectthat is packaged within the EAR. You will mark this project as an EJB module later in theapplication.xml.

  • 8/3/2019 Building EJB 3

    9/65

    F igure 10. Select Utility Project

    i. Name the project OrderSystemEJB (Figure 11). Ensure that the EAR Project Name matches thealready created EAR project.

    F igure 11. Utility Project Wizard

  • 8/3/2019 Building EJB 3

    10/65

    2. You now need to update the EAR file so that it sees the Java project as an EJB Module:a. Expand the O rderSystem and double click the Deployment Descriptor Editor (Figure 12).

  • 8/3/2019 Building EJB 3

    11/65

    F igure 12. O pen Deployment Descriptor

    b. Go to the source tab, shown in Figure 13. Add these XML fragments after the display name tag:

    OrderSystemEJB.jar

    c.d. The result should look similar to Figure 13e.

    F igure 13. application.xml

    f. Save the editor and close the Application Deployment Descriptor.3. Add the local WebSphere Application Server to the Application Server Toolkit workspace as a server:

    a. In the J2EE perspective, go to the Servers tab. Right-click within the servers list andselect New=>Server (Figure 14).

    F igure 14. New Server

  • 8/3/2019 Building EJB 3

    12/65

    b. Accept the defaults, then Next .c. Un-check Run server with resources within the workspace , then F inish .

    F igure 15. WebSphere Server Settings

  • 8/3/2019 Building EJB 3

    13/65

    d. Right-click on the new server and select Start .4. Add a data source for the Derby database that you populated with the CUSTSCH schema provided in

    CUSTSCH-derby.ddl:a. Right-click on the server and select Run administrative console (Figure 16).

    F igure 16. Launch administrative console

  • 8/3/2019 Building EJB 3

    14/65

    b. In the administrative console, navigate to Resources=> J DB C=>Data sources .c. Select a scope for the data source (Figure 17). What you choose will vary depending on your

    installation. Select a server scope for your local server, then click New .

    F igure 17. Create a DataSource

    d. On the Step 1 panel (Figure 18), enter Ord e r DS for the Data source nameand j db c/o rd e rd s for the JNDI name, then Next .

    F igure 18. DataSource wizard

  • 8/3/2019 Building EJB 3

    15/65

    e. On the Step 2 panel (Figure 19), select Create new J DB C Provider , then Next .

    F igure 19. J DB C Provider

    f. On the Step 2.1 panel (Figure 20), select the following values: Database type: Derby Provider type: Derby Network Server Using Derby Client Implementation type: Connection pool data source

    Enter optional Description text, then click Next .

  • 8/3/2019 Building EJB 3

    16/65

    F igure 20. J DB C Provider

    g. On the Step 3 panel (Figure 21), enter JPATE S T for the database name, then Next .

    F igure 21. Database Specific Properties

  • 8/3/2019 Building EJB 3

    17/65

    h. On the Step 4 panel (Figure 22), review the data to make sure all values were entered correctly,then click F inish .

    F igure 22. Summary

  • 8/3/2019 Building EJB 3

    18/65

    i. Save your changes by clicking the Save link at the top of the page. j. Verify that the Derby network database is running, then select the O rder DS data source and

    click Test Connection (Figure 23).

    F igure 23. Test Connection

    k. You should receive a message at the top of the panel similar to that shown in Figure 24

    F igure 24. Connection Confirmation

    B . Create your first J PA P O J O The EJB 3.0 specification defines a new persistence architecture, called the Java Persistence Architecture (JPA), thatenables you to map simple POJOs to relational databases. JPA POJOs are no longer EJB components. Instead, the

    EJB 3.0 spec defines how JPA objects are managed in an EJB 3.0 container. However, JPA applications can runinside a Java SE environment as well. In this example, you will to create a JPA object that runs inside WebSphere Application Server.

    1. First, create a simple POJO:a. Expand the O rderSystem EJB project. Right-click on the src directory and select New =>

    Class (Figure 25).

  • 8/3/2019 Building EJB 3

    19/65

    F igure 25. New Class

    b. In the New Java Class panel (Figure 26), store the class in the Packagecalled com.i b m.ej b3 .o rd e r .entities , name the class Custome r , then F inish .

  • 8/3/2019 Building EJB 3

    20/65

    F igure 26. Class Wizard

    c. Create two simple properties: customerId: int name: String

    p ackage com.ibm.ejb3.order.entities;

    im p ort java.io.Serializable;

    p ublic class Customer im p lements Serializable{

    p rivate int customerId;p rivate String name;

    }

    d.e. In the Ourtline view, right-click on the Customer class, then select Source => Generate Getters

    and Setters (Figure 27).

  • 8/3/2019 Building EJB 3

    21/65

    F igure 27. Generate Getters and Setters

    f. Click Select All and OK (Figure 28).

  • 8/3/2019 Building EJB 3

    22/65

    F igure 28. Select properties

    g. The result is a simple POJO, as shown in Figure 29.

  • 8/3/2019 Building EJB 3

    23/65

    F igure 29. Customer Class

    2. You are now ready to make your POJO a JPA entity. In most cases, all you need is a good Java editor. This

    example uses the editor in Eclipse that you use to create JPA applications:a. Over the class declaration, begin typing @E nti , then press Ctrl-Space to trigger the Eclipsecontent assist. Select @E ntity . (Figure 30)

  • 8/3/2019 Building EJB 3

    24/65

    F igure 30. E ntity Annotation

    b. An Entity class needs a primary key. Over the customerId property, add the @I d annotation (Figure

    31).

    F igure 31. Id Annotation

  • 8/3/2019 Building EJB 3

    25/65

    3. If your property names match that of the database, you are done and you have your first JPA POJO.However, the schema in this example is slightly different, and you will use the JPA Eclipse tools for help:

    a. Switch to the J ava Persistence perspective. You can begin the Open Perspective wizard by right-clicking on the perspective icons in the upper right corner of the panel and selecting O ther . (Figure32)

  • 8/3/2019 Building EJB 3

    26/65

    F igure 32. O pen O ther

    b. Select J ava Persistence from the list that displays.c. Go to the Database E xplorer view. To load your database, right-click on Connections , then

    select New => Connection... (Figure 33)

    F igure 33. New Connection

    d. Enter or select the following properties (Figure 34): Uncheck Use default naming convention Connection Name: Ord e r DB Database Manager: Derby => 10.1 Database Name: JPATE S T Class Location: navigate to Derby lib directory (for example:

    \WebSphere\AppServer\derby\lib\derbyclient.jar) User Id and Password: Enetr appropriate values for your system.

    F igure 34. Connection Parameters

  • 8/3/2019 Building EJB 3

    27/65

    e. Navigate to O rderD B => J PAT E ST => Schemas => CUSTSCH => Tables => CUST O ME R andexamine the fields (Figure 35).

    F igure 35. CUST O ME R Table

  • 8/3/2019 Building EJB 3

    28/65

    4. You need to add the persistence.xml file to the JPA project. This file is the JPA deployment descriptor for configuring JPA Properties. You can use the JPA development tools for this:

    a. In the Package Explorer view, right-click O rderSystem EJB and select J ava Persistence => AddJ ava Persistence... (Figure 36)

  • 8/3/2019 Building EJB 3

    29/65

    F igure 36. Add J ava Persistence support

    b. For Connection, select O rderD B , and for Schema, select CUSTSCH . (The connection could havetimed out. If so, select the Reconnect... link and enter the same user ID and password). For Persistence unit name, enter Ord e r DB (Figure 37).

  • 8/3/2019 Building EJB 3

    30/65

    F igure 37. J PA Project Content

    c. Once you do this, your Customer POJO will have an error because the Eclipse JPA plug-in willdetect a mismatch between the database model and the JPA object model. You will fix this in thenext step.

    d. Open the ME TA- INF folder of OrderSystemEJB, and open the newly generated persistence.xml(Figure 38).

  • 8/3/2019 Building EJB 3

    31/65

    F igure 38. persistence.xml

    e. You need to add the data source to the JPA provider. Open persistence.xml and click on

    the Source tab. Add this xml tag within the persistence-unit tag, as shown in Figure 39:jdbc/orderds

    f.

    F igure 39. Adding DataSource

    g. Save and close persistence.xml. (Because you are running inside a Java EE container, the defaultprovider will be used.)

    5. Because the database does not match exactly with your POJO, you need to fix your mappings a bit:a. In the Outline view, select the customer Id property.b. In the lower right corner of the panel, ensure that Map As is set to Id. Under Column Name,

    select CUST_ ID. Ensure the rest of the fields match the values shown in Figure 40.

    F igure 40. Persistence Properties

  • 8/3/2019 Building EJB 3

    32/65

    c. Select the P K Generation tab. Check the Primary K ey Generation and select Identity for Strategy (Figure 41). JPA enables a few strategies for automatic primary key generation. In thiscase, JPA will delegate to DB2's identity feature.

    F igure 41. Identity Strategy

    d. In the Customer POJO, you need to override the default schema name because the database isstored in a different schema. Add the @T a b le annotation as shown in Figure 42.

    Add CUST OM ER for name and CUST SCH for schema.

  • 8/3/2019 Building EJB 3

    33/65

    F igure 42. Set Schema

    e. Save and close Customer.java.C. Create a simple sessions bean Much like JPA, all of EJB 3.0 has been simplified with a POJO programming model, making EJB 3.0 easy to code.Below, you will create a simple session bean that uses the JPA API to access the Customer JPA POJO.

    1. First, you need to create a simple interface; having an interface is usually a good practice. Otherwise, theEJB provider will generate one for you. In this exercise, you will just create a simple Interface.

    a. Under the OrderSystemEJB project, right-click the src folder and select New=> Interface (Figure43).

  • 8/3/2019 Building EJB 3

    34/65

    F igure 43. New Interface

    b. For Package name, enter or browse to com.ibm.ejb3.order.session . For class name,enter Custome r T ask (Figure 44).

  • 8/3/2019 Building EJB 3

    35/65

    F igure 44. Interface Wizard

    c. Add the method below to the interface, then F inish .

    p ublic Customer findCustomer(int customerId) throws CustomerDoesNotExist ;

    d.e. You should have an error, because there is no class called CustomerDoesNotExist. Use the

    Eclipse suggestion to create the class, as in Figure 45.

    F igure 45. Create E xception

  • 8/3/2019 Building EJB 3

    36/65

    f. Make sure that Constructors from superclass is checked and that the superclassis java.lang. E xception (Figure 46).

    F igure 46. Class Wizard

    g. Next, add a @L ocal annotation above the class declaration, as shown in the Figure 47. Thismakes your session bean a local EJB.

    F igure 47. Local Annotation

  • 8/3/2019 Building EJB 3

    37/65

    h. Right click in the editor and select Source => O rganize Imports (Figure 48)

    F igure 48. Adding Imports

    2. Next, you will create your Session Bean POJO:a. Right-click the com.ibm.ejb3.order.session package and select New => Class (Figure 49).

  • 8/3/2019 Building EJB 3

    38/65

    F igure 49. New Class

    b. Name the class Custome r T ask I mpl , and add the CustomerTask interface to the Interface list

    (Figure 50).

  • 8/3/2019 Building EJB 3

    39/65

    F igure 50. Class Wizard

    c. To make CustomerTaskImpl a session bean, add an @Stateless annotation, as shown inFigure 51. This makes your POJO a stateless session bean.

    F igure 51. Stateless Annotation

  • 8/3/2019 Building EJB 3

    40/65

    3. An EJB 3.0 container is also an injection server. To have persistence actions, you need an entity manager.This can be easily added to the session bean through injection. When using JPA within an EJB 3.0container, the container automatically manages passing the correct persistence context for you. This isknown as a container managed entity manager. Using JPA in this fashion, the EJB 3.0 container willproperly manage the lifecycle of the persistence context, and propagate the correct context across EJBinvocations.

    a. Add the EntityManager declaration shown below to the CustomerTaskImpl class.

    @PersistenceContext(name="OrderDB")EntityManager em;

    b.

    c. You can use code assist to bring in the PersistenceContext Import (Figure 52).

    F igure 52. PersistenceContext Annotation

    d. Add this code snippet to the findCustomer method:

    Customer customer = (Customer) em.find(Customer.class, customerId);if (customer == null) {

    throw new CustomerDoesNotExist("Customer does not exist");}return customer;

    e.f. Organize imports as before (Figure 53), then save and close the file.

  • 8/3/2019 Building EJB 3

    41/65

    F igure 53. Customer implementation

    D. Import the client Next, you will import a simple WAR file with a servlet that will be used to test your session bean and JPA object. Theservlet demonstrates how easy it is to access a session bean from Web applications. A simple WAR file is includedwith this article with the code already in place.

    1. Import the Web application and examine the code:a. From the File Menu, select F ile => Import .b. In the Import wizard, expand Web => WAR F ile (Figure 54).

  • 8/3/2019 Building EJB 3

    42/65

    F igure 54. Import WAR F ile

    c. For WAR file, B rowse to the location where you saved the provided OrderClient.war file. Keep thedefault name for the Web project, and ensure that O rderSystem is the EAR Project Name (Figure55).

  • 8/3/2019 Building EJB 3

    43/65

    F igure 55. Select E AR Project to Import to

    2. Next, you can examine the servlet code.a. Expand the J ava Resources: src folder and open the EJB ClientServlet.java file (Figure 56).

  • 8/3/2019 Building EJB 3

    44/65

    F igure 56. Test Servlet

    b. Notice that the EJB session bean can be injected right into the servlet.

    p ublic class EJBClientServlet extends javax.servlet.htt p .Htt p Servletim p lements javax.servlet.Servlet {

    /* (non-Java-doc)* @see javax.servlet.htt p .Htt p Servlet#Htt p Servlet()*/

    @EJBp rivate CustomerTask customerTask = null;

    c.d. In the displayCustomerAndOrder method, notice that once you have the session bean instance, it

    is just simple Java.

    p rivate void dis p layCustomerAndOrder(int customreId, P rintWriter out) throwsCustomerDoesNotExist {

    Customer customer = customerTask.findCustomer(customreId);out. p rintln("
    Customer ID => " + customer.getCustomerId());

    out. p rintln("
    Customer Name => " + customer.getName());

    e.3. You will now deploy and test the application:

    a. From the J2EE perspective, go to the Servers view, right-click the server and press Start (Figure

    57).

  • 8/3/2019 Building EJB 3

    45/65

    F igure 57. Start the Server

    b. Once the server is started, right-click the server again and select Add and RemoveProjects... (Figure 58)

    F igure 58. Add the Project

    c. Add the OrderSystem application by selecting the application from the Available projects list onthe left and press Add (Figure 59).

  • 8/3/2019 Building EJB 3

    46/65

    F igure 59. Move project

    d. Back in the Project Explorer view, expand the Deployment Descriptor => Servlets , then right-clickEJB ClientServlet and select Run As => Run on Server (Figure 60).

  • 8/3/2019 Building EJB 3

    47/65

    F igure 60. Run the Servlet

    e. Select Choose an existing server and check the Set server as project default option,then F inish (Figure 61).

  • 8/3/2019 Building EJB 3

    48/65

    F igure 61. Associate Server as default

    f. The browser should display the Customer ID and Customer Name (Figure 62).

    F igure 62. E xamine B rowser

  • 8/3/2019 Building EJB 3

    49/65

    g. Close the browser and remove the project from the server (Figures 63 and 64)

    F igure 63. Remove the Project

  • 8/3/2019 Building EJB 3

    50/65

    F igure 64. Remove the Project

    h. Close and save all the files.B ack to top

    Advanced EJB features EJB 3.0 provides a simple programming model without compromising function. The fundamental principal is to usedefault values, and only override where you must. For example, EJB 3.0 still permits XML configuration. XMLdeployment descriptors can override annotations so you can externalize configurations and override settings for different deployment environments. In this section, you will continue to use annotations, but will add morefunctionality to the application to see some other features of EJB 3.0. (The application used here was designed solelyfor illustrating different EJB 3.0 and JPA features, and not to be an example of application design best practices.)The steps in this section:

    A. Building JPA objects B. Build another session bean

    C. Add an interceptor D. Test the application A. B uilding J PA objects The steps below show how to use the JPA Eclipse tools to generate more JPA POJOs, after which you will updatethe mappings to customize for the use case.

    1. The JPA Eclipse tools support top-down, meet-in-the-middle, and bottom-up mappings. You will use thebottom-up tools to generate the remaining entities:

    a. In the Package E xplorer view, right-click O rderSystem EJB and select J ava Persistence =>Generate E ntities (Figure 65).

  • 8/3/2019 Building EJB 3

    51/65

    F igure 65. Generate E ntities

    b. Select your Connection (your database connection may have closed by now; selectthe Reconnect link and enter your credentials again, if necessary), and selectthe CUSTSCH schema. Press Next (Figure 66).

  • 8/3/2019 Building EJB 3

    52/65

    F igure 66. Select Connection and Schema

    c. On the Generate Entities from Tables panel, only select LINEI TE M, CUST O RD E R,and PR O DUCT . Make sure your Package name is com.ibm.ejb3.order.entities . Since theCUSTORDER table name is different than the Entity Name ("Order," which is the desired name of the entity), enter Ord e r as the Entity name for CUSTORDER (Figure 67). Press F inish .

    F igure 67. Select the Tables

  • 8/3/2019 Building EJB 3

    53/65

    2. Next, you will update the mappings:a. Open the Order entity (Figure 68).

    F igure 68. E xamine O rder Class

  • 8/3/2019 Building EJB 3

    54/65

    b. Use the Java Persistence Properties Editor or add the annotations marked below in bold: @Table annotation is needed to override the schema name. @NamedQuery is adding a query to your JPA POJO. JPA has a very rich query language

    you can use, called EJB-QL. This query is asking for an open order from the customer. The ordered property needs to be annotated as an ID, as you did before. Also, you are

    adding a generation strategy of Identity. Finally, notice the Order has a relationship to LineItems. You will add a fetch rule of Eager.

    This means that when someone asks for an order, the JPA engine will fetch all the lineitems that are associated with the order as well.

    @Entity@Table(name="CUSTORDER", schema="CUSTSCH")@NamedQuery(name="getCurrentOrder",query="select o f rom Order o where o.customerId = :customerId and

    o.status ='O P EN'")p ublic class Order im p lements Serializable {@Id

    @Column(name="ORDER_ID")@GeneratedValue(strategy= GenerationTy p e.IDENTITY)p rivate int orderId;

    p rivate String status;

    p rivate double total;

  • 8/3/2019 Building EJB 3

    55/65

    @Column(name="CUSTOMER_ID")p rivate int customerId;

    @OneToMany(ma pp edBy="orderId",fetch=FetchTy p e.EA GER)p rivate Set lineitemCollection;

    c.3. You need to update the Customer entity to have a relationship to Order. The requirements of the system are

    such that a Customer has only one open Order. You want to create a relationship to that open Order. Youdo not want to generate the relationship because a Customer has many orders, but only when he has oneOpen Order.

    a. Open the Customer entity. Add Order currentOrder, as shown in the code below. Generate thesetters and getters using the Eclipse Java tools.

    p ackage com.ibm.ejb3.order.entities;

    im p ort java.io.Serializable;im p ort javax. p ersistence.Entity;im p ort javax. p ersistence.Id;im p ort javax. p ersistence. GeneratedValue;im p ort javax. p ersistence. GenerationTy p e;im p ort javax. p ersistence.Column;im p ort javax. p ersistence.Table;

    @Entity@Table(name="CUSTOMER", schema="CUSTSCH")p ublic class Customer im p lements Serializable {

    @Id@GeneratedValue(strategy= GenerationTy p e.IDENTITY)@Column(name="CUST_ID")p rivate int customerId;p rivate String name;

    p rivate Order currentOrder;

    p ublic int getCustomerId() {return customerId;

    }p ublic void setCustomerId(int customerId) {this.customerId = customerId;

    }p ublic String getName() {

    return name;}p ublic void setName(String name) {

    this.name = name;}p ublic Order getCurrentOrder() {

    return currentOrder;}p ublic void setCurrentOrder(Order currentOrder) {

    this.currentOrder = currentOrder;}

    }

    b.c. Add the following @O ne T o O ne and @J oinColumn annotations, as shown below.

    Notice that the fetch rule is set to lazy, so you will not fetch the order when someone asksfor the customer.

    You have set some cascading rules. If someone updates the open order, changes willcascade as defined.

    The relationship is optional, which means the customer will not always have an openorder.

  • 8/3/2019 Building EJB 3

    56/65

    You have specified the Join column (the name corresponds to the foreign key on theCustomer table, while the referencedColumn name corresponds to the primary key of theCustorder table.) If you do not specify the Join column, JPA will attempt to resolve thekeys based on a naming scheme.

    @OneToOne(fetch=FetchTy p e. LAZY,cascade ={CascadeTy p e.MER GE,CascadeTy p e.REFRESH},o p tional=true )

    @JoinColumn(name="O PEN_ORDER_ID",referencedColumnName="ORDER_ID")p rivate Order currentOrder;

    d.e. Update the LineItem class to point to the correct schema, as you did for Customer and Order

    (Figure 69).

    F igure 69. Line Item Schema

    f. Similarly, override the schema for Product (Figure 70).

    F igure 70. Product Schema

    g. Save and close the entities.B . B uild another session bean Here, you will build another session bean to see how you can inject another session bean into it.

    1. As before, create an interface:

  • 8/3/2019 Building EJB 3

    57/65

    a. In the session package, select New => Interface (Figure 71) and name the Interface O rderTask .Click F inish .

    F igure 71. New Interface

    b. Annotate the class as Local , and add the getCurrentOrder method, as shown below.

    p ackage com.ibm.ejb3.order.session;

    im p ort com.ibm.ejb3.order.entities.Order;

    @Localp ublic interface OrderTask {

    p ublic Order getCurrentOrder(int customerId) throws CustomerDoesNotExist;}

    c.2. Create a new stateless session bean.

    a. Right-click the session 's package and select New => Class (Figure 72).

    F igure 72. New Class

  • 8/3/2019 Building EJB 3

    58/65

    b. Make sure the class implements the OrderTask Interface you just created (Figure 73).

    F igure 73. O rderTask Impl

    c. Annotate the bean as stateless. Add the code in bold below. Notice that you can inject theCustomerTask into the OrderTask. This greatly simplifies things by avoiding JNDI lookup code.

    Also, you are also injecting an entity manager, as you did before.

    p ackage com.ibm.ejb3.order.session;

    im p ort javax.ejb.EJB;im p ort javax.ejb.Stateless;

    im p ort com.ibm.ejb3.order.entities.Order;

    @Statelessp ublic class OrderTaskIm p l im p lements OrderTask {

  • 8/3/2019 Building EJB 3

    59/65

    @EJB(beanName = "CustomerTaskIm p l")CustomerTask customerTask;

    @PersistenceContext(name="OrderDB")EntityManager em;

    p ublic Order getCurrentOrder(int customerId) throws CustomerDoesNotExist {// TODO Auto-generated method stubreturn null;

    }

    }

    d.e. Finally, add the code in bold below to the getCurrentOrder method. Notice how easy it is to access

    queries. Also notice that the order method interacts with the Customer object. It is important tounderstand that because both classes are using @PersistenceContext, they will get proper propagation of the Entity Manager.

    p ublic Order getCurrentOrder(int customerId) throws CustomerDoesNotExist {Query query = em.createNamedQuery("getCurrentOrder");query.set Parameter(1, customerId);Order currentOrder = (Order)query.getSingleResult();if(currentOrder != null){

    Customer customer = customerTask.findCustomer(customerId);Order alreadySet = customer.getCurrentOrder();if(alreadySet == null){

    customer.setCurrentOrder(currentOrder);}

    }return currentOrder;

    }

    f.g. Don't forget to organize your imports.

    C. Add an interceptor EJB 3.0 also adds the ability to use Aspect Oriented Programming techniques in your application. EJB 3.0 supports

    interceptors, which enable you to intercept code for cross cutting techniques. Next, you will create an audit interceptor that displays the customer's actions on the administrative console.1. Create a simple Audit class:

    a. Create a class called AuditInterceptor (Figure 74).

  • 8/3/2019 Building EJB 3

    60/65

    F igure 74. New J ava Class

    b. Add the code below in bold. @AroundInvoke tells the container what method to call when theinterceptor intercepts. The code accesses the customerId and method name and displays them.

    p ackage com.ibm.ejb3.order.session;

    im p ort java.lang.reflect.Method;

    im p ort javax.interce p tor.AroundInvoke;im p ort javax.interce p tor.InvocationContext;

    p ublic class AuditInterce p tor {

    @AroundInvokep ublic Object audit(InvocationContext invocationContext) throws Exce p tion{

    Method o p eration = invocationContext.getMethod();String name = o p eration.getName();

  • 8/3/2019 Building EJB 3

    61/65

    Object p aram[] = invocationContext.get Parameters();System.out. p rintln("Customer Id " + p aram[0] + " executing o p eration =

    + name);return invocationContext. p roceed();

    }

    }

    c.2. You can add the interceptor to the session beans by annotating the class with the @Interceptor annotation.You will do this for simplicity in this exercise, but it is often a best practice for a class not to be aware of whois intercepting it. EJB 3.0 supports partial XML deployment descriptors where you can define interceptor bindings that externalize matching an interceptor to a class. It is usually best to externalize interceptors.

    a. Open the OrderTaskImpl class and add the @Interceptors (AuditInterceptors.class), as shownbelow.

    @Stateless@Interce p tors(AuditInterce p tor.class)p ublic class OrderTaskIm p l im p lements OrderTask {

    b.c. Do the same for the CustomerTask.

    @Stateless@Interce p tors(AuditInterce p tor.class)p ublic class CustomerTaskIm p l im p lements CustomerTask {

    d.D. Test the application You need to modify the client to invoke the new function:

    1. The code you need is provided with this article, but it is commented out. Uncomment the OrderTaskdeclaration as shown below in bold.

    p ublic class EJBClientServlet extends javax.servlet.htt p .Htt p Servlet im p lementsjavax.servlet.Servlet {

    /* (non-Java-doc)* @see javax.servlet.htt p .Htt p Servlet#Htt p Servlet()*/

    @EJBp rivate CustomerTask customerTask = null;

    @EJBp rivate OrderTask orderTask = null;

    p ublic EJBClientServlet() {su p er();

    }

    @Overridep ublic void init() throws ServletExce p tion {

    su p er.init();}

    2.

    3. Uncomment the code in bold below. Notice that you access the Order and Iterate functions through theLineItems. The LineItems will be populated because of the eager fetching rule you set.

    p rivate void dis p layCustomerAndOrder(int customerId, P rintWriter out) throwsCustomerDoesNotExist {

    Customer customer = customerTask.findCustomer(customerId);out. p rintln("
    Customer ID => " + customer.getCustomerId());out. p rintln("
    Customer Name => " + customer.getName());

    Order order = o rderTask.getCurrentOrder(customerId);if(order != null)

  • 8/3/2019 Building EJB 3

    62/65

    {out. p rintln("
    order id => " + order.getOrderId());out. p rintln("
    status => " + order.getStatus());out. p rintln("
    Total => " + order.getTotal());Collection lineItems = order.getLineitemCollection();for(Lineitem lineItem: lineItems){

    out. p rintln("
    ****");out. p rintln("
    Line Item Id => " + lineItem.getLiId());out. p rintln("
    Quantity => " + lineItem.getQuantity());out. p rintln("
    Total => " + lineItem.getAmount());

    }

    }else{

    out. p rintln("
    Customer has no o p en order...");}

    }

    4.5. Add the project to the server as you did before (Figure 75).

    F igure 75. Add Project Again

    6. Run the servlet (Figure 76).

  • 8/3/2019 Building EJB 3

    63/65

    F igure 76. Run on Server

    7. The browser should display the customer, the current order, and all the line items (Figure 77).

  • 8/3/2019 Building EJB 3

    64/65

    F igure 77. E xamine Result

    8. Finally, examine the console to see the print statements for the interceptor (Figure 78). You will notice thefindCustomer task is called twice, once from the client and once from the order task, and thegetCurrentOrder task is called once.

    F igure 78. E xamine Interceptor result

    B ack to top

    Conclusion EJB 3.0 is a major step forward in simplifying application development in the enterprise. This article showed you howto build EJB 3.0 applications for WebSphere Application Server V6.1 using the simplified programming model, the

  • 8/3/2019 Building EJB 3

    65/65

    new Java Persistence API, and interceptors. By using the EJB 3.0 Feature Pack for WebSphere Application Server,you can benefit from the simplified development experience, new persistence model, and new features such asinterceptors, while still deploying to a robust WebSphere platform.

    B ack to top

    Acknowledgements The authors wish to acknowledge Tom Alcott, Jim Knutson, Randy Schnier, Kevin Sutter, Tim Francis, and KeysBotzum for their contributions to the article.

    B ack to top

    Download

    Description Name Size Download method

    Code sample WAS_EJB3_LAB.zip 10 KB HTTP

    Information about download methods