Chapter 10. Using EJBs

Table of Contents

10.1. Session Bean Example
10.1.1. Sample Code
10.1.2. Compilation
10.1.3. Deployment
10.1.4. Execution Result
10.2. Java Persistence API Example
10.2.1. Sample File
10.2.2. Compilation
10.2.3. Deployment
10.2.4. Execution Result

This chapter provides examples of developing and deploying an entity using stateless session beans and the Java Persistence API.

10.1. Session Bean Example

A session bean consists of a business interface and a bean class.

10.1.1. Sample Code

Example of an EJB

The following example shows a stateless session bean that has a method that displays helloejb.

  • Business Interface

    [Example 10.1] <<Hello.java>>

    package helloejb;
    
    import javax.ejb.Remote;
    
    @Remote
    public interface Hello {
        String sayHello();
    }


  • Bean Class

    [Example 10.2] <<HelloBean.java>>

    package helloejb;
    
    import javax.ejb.Stateless;
    
    @Stateless(mappedName="helloejb.Hello")
    public class HelloBean implements Hello {
    
        public String sayHello() {
            return "Hello EJB!";
        }
        
    }


The sample file is in the following path.

JEUS_HOME/samples/getting_started/helloejb/helloejb-ejb/src/java/helloejb

Example of a Servlet Client

The following is the implementation of a servlet client that calls helloejb.

[Example 10.3] <<HelloClient.java>>

package helloejb;

import java.io.*;
import javax.ejb.EJB;

import javax.servlet.*;
import javax.servlet.http.*;

public class HelloClient extends HttpServlet {
    @EJB(mappedName="helloejb.Hello")
    private Hello hello;

    protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            // Call session bean business method.
            String msg = hello.sayHello();
            
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>HelloClient</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<center><h1>" + msg + "</h1></center>");
            out.println("</body>");
            out.println("</html>");
            out.close();
        } catch(Exception ex){
            response.setContentType("text/plain");
            ex.printStackTrace(out);
        }
    }
    
    protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    protected void doPost(HttpServletRequest request, 
        HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
}


The sample file is in the following path.

JEUS_HOME/samples/getting_started/helloejb/helloejb-war/src/java/helloejb

10.1.2. Compilation

The sample code can be built using jant as in the following.

%JEUS_HOME%/samples/getting_started/helloejb>jant build

After the sample code has been built successfully, an EAR file is created as '%JEUS_HOME%/samples/getting_started/helloejb/dist/helloejb.ear'.

10.1.3. Deployment

A packaged EJB application can be deployed using WebAdmin or console.

Deploying an EJB Application in WebAdmin

This section describes how to deploy an EJB application in WebAdmin.

  1. Log in to WebAdmin using a web browser.

  2. Click [Applications] from the left pane to go to the application list page.

    Click [Install] from the Deployed Applications page.

    [Figure 10.1] Applications Installed on DAS

    Applications Installed on DAS

  3. Enter the ID in the 'Id' field of the Install page. Click [Browse...] next to the Path option to search for a target application and then click [OK].

    [Figure 10.2] Selecting a Target Application

    Selecting a Target Application


  4. The list of applications deployed on DAS is shown on the Deployed Applications page. Click [Deploy] to deploy the application to an MS.

    [Figure 10.3] List of Installed Applications

    List of Installed Applications


  5. Select the server to deploy and click [OK]. It is possible to select DAS, but an MS is recommended for deployment.

  6. The following message is displayed after the EJB application has been deployed successfully.

    [Figure 10.4] Deployment Successful Message

    Deployment Successful Message

Deploying an EJB Application in the Console

This section describes how to deploy an EJB application in the console.

  1. Find the helloejb.ear file that was created.

  2. Log in to JEUS as jeusadmin.

    jeusadmin johan –u administrator –p <password>
  3. Install the application on DAS.

    [DAS]jeus_domain.adminServer>install-application -id helloejb C:\TmaxSoft\JEUS8\samples\getting_started\helloejb\dist\helloejb.ear
    Successfully installed application[helloejb].
  4. Deploy the application to an MS (Server1).

    [DAS]jeus_domain.adminServer>deploy helloejb -servers server1
    Succeeded to deploy the application : helloejb

10.1.4. Execution Result

This section describes how to execute and test the deployed application.

To execute HelloEJB:

  1. Open a browser window and enter the following URL into the address bar.

    http://localhost:8088/helloejb/

    [Figure 10.5] HelloEJB Client Page

    HelloEJB Client Page

  2. Click [Invoke HelloEJB Client] to execute the HelloClient servlet that invokes the EJB. The following result will appear.

    [Figure 10.6] HelloEJB Servlet Execution Result

    HelloEJB Servlet Execution Result

10.2. Java Persistence API Example

This section describes how to develop an entity using the Java Persistence API and how to compile and deploy the entity.

10.2.1. Sample File

EJB Example

The sample code consists of a product entity and the ProductManager session bean that processes the entity.

  • Entity

    [Example 10.4] <<Product.java>>

    package hellojpa;
    
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.NamedQuery;
    
    @Entity
    @NamedQuery(name="findAllProducts", query="SELECT p FROM Product p")
    public class Product implements Serializable {
        @Id
        private String productId;
        private double price;
        private String description;
        
        public Product() {
        }
        
        public Product(String productId, double price,
            String description){
            this.productId = productId;
            this.price = price;
            this.description = description;
        }
    
        public String getProductId() {
            return productId;
        }
    
        public void setProductId(String id) {
            this.productId = id;
        }
    
        public double getPrice() {
            return price;
        }
    
        public void setPrice(double price) {
            this.price = price;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
        
        public String toString() {
            return "Product[productId=" + productId + ", price=" +
                price + ", description=" + description + "]";
        }
    }


  • Business Interface

    [Example 10.5] <<ProductManager.java>>

    package hellojpa;
    
    import java.util.Collection;
    import javax.ejb.Local;
    
    @Local
    public interface ProductManager {
        Product createProduct(String productId, double price, String desc);
        
        Product getProduct(String productId);
        
        Collection findAllProducts();
        
        Collection findProductsByDescription(String desc);
    
        Collection findProductsInRange(double low, double high);
        
        void updateProduct(Product product);
        
        void removeProduct(Product product);
        
        void removeAllProducts();
    }


  • Bean Class

    [Example 10.6] <<ProductManagerBean.java>>

    package hellojpa;
    
    import java.util.Collection;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Stateless(mappedName="hellojpa.ProductManager")
    public class ProductManagerBean implements ProductManager {
        @PersistenceContext
        private EntityManager em;
        
        public ProductManagerBean() {
        }
    
        public Product createProduct(String productId, double price, String desc){
            Product product = new Product(productId, price, desc);
            em.persist(product);
            return product;
        }
        
        public Product getProduct(String productId){
            return (Product)em.find(Product.class, productId);
        }
        
        public Collection findAllProducts() {
            return em.createNamedQuery("findAllProducts").getResultList();
        }
    
        public Collection findProductsByDescription(String desc){
            Query query = em.createQuery("SELECT p FROM Product p WHERE  
                p.description=:desc");
            query.setParameter("desc", desc);
            return query.getResultList();
        }
    
        public Collection findProductsInRange(double low, double high){
            Query query = em.createQuery("SELECT p FROM Product p WHERE 
                p.price between :low and :high");
            query.setParameter("low", low).setParameter("high", high);
            return query.getResultList();
        }
        
        public void updateProduct(Product product){
            Product managed = em.merge(product);
            em.flush();
        }
        
        public void removeProduct(Product product){
            Product managed = em.merge(product);
            em.remove(managed);
        }
        
        public void removeAllProducts(){
            em.createQuery("DELETE FROM Product p").executeUpdate();
        }
    }


The sample file is in the following path.

JEUS_HOME/samples/getting_started/hellojpa/hellojpa-ejb/src/java/hellojpa

Servlet Client Example

A servlet client that saves and processes data in a database by using the ProductManager EJB is implemented as in the following.

[Example 10.7] <<ProductManagerClient.java>>

package hellojpa;

import java.io.*;
import java.util.Collection;
import javax.ejb.EJB;

import javax.servlet.*;
import javax.servlet.http.*;

public class ProductManagerClient extends HttpServlet {
    @EJB
    private ProductManager productManager;    

    protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {        
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("SERVLET CLIENT CONSOLE OUTPUT:\n");
        
        productManager.removeAllProducts();
        out.println("Cleaned up existing products.\n");
        
        out.println("Creating products...");
        Product p1 = productManager.createProduct("1", 10.00, "Ceramic Dog");
        Product p2 = productManager.createProduct("2", 13.00, "Wooden Duck");
        Product p3 = productManager.createProduct("3", 19.00, "Ivory Cat");
        Product p4 = productManager.createProduct("4", 33.00, "Ivory Cat");
        Product p5 = productManager.createProduct("5", 22.00, "Chrome Fish");
        
        Collection products;

        out.println("Created products:");
        products = productManager.findAllProducts();
        for(Object product : products){
             out.println(product);
        }
        out.println();
        
        out.println("Find product with productId 1:");
        Product pp1 = productManager.getProduct("1");
        out.println("Found = " + pp1.getDescription() + " $" + pp1.getPrice());
        
        out.println("Update the price of this product to 12.00");
        pp1.setPrice(12.00);
        productManager.updateProduct(pp1);
        
        Product pp2 = productManager.getProduct("1");
        out.println("Product " + pp2.getDescription() + " is now $" + pp2.getPrice());
        out.println();
        
        out.println("Find products with description:");
        products = productManager.findProductsByDescription("Ivory Cat");
        for(Object product : products){
            out.println(product);
        }
        out.println();
        
        out.println("Find products with price range between 10.00 and 20.00");
        products = productManager.findProductsInRange(10.00, 20.00);
        for(Object product : products){
            out.println(product);
        }
        out.println();
        
        out.println("Removed all products.");
        productManager.removeProduct(p1);
        productManager.removeProduct(p2);
        productManager.removeProduct(p3);
        productManager.removeProduct(p4);
        productManager.removeProduct(p5);
        
        out.close();
    }
    
    protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}


The sample file is in the following path.

JEUS_HOME/samples/getting_started/hellojpa/hellojpa-war/src/java/hellojpa

10.2.2. Compilation

The following are the steps for compiling the sample code using jant.

  1. Execute the jant build command from the directory of the sample code file.

    C:\TmaxSoft\JEUS8\samples\getting_started\hellojpa>jant build
  2. After the sample code has been built correctly, the 'dist/hellojpa.ear' EAR file is created.

    Since this example requires a database, Derby must be running. Configure the database with the 'jdbc/sample' data source. For detailed information, refer to "Chapter 8. Configuring a JEUS System" .

    After Derby has been started, create the following database table. In this example, a database named 'sample' is used.

    CREATE TABLE PRODUCT (PRODUCTID VARCHAR(255) NOT NULL, PRICE FLOAT,
        DESCRIPTION VARCHAR(255), PRIMARY KEY (PRODUCTID));
  3. Create the database table by executing the jant setup command as in the following.

    C:\TmaxSoft\JEUS8\samples\getting_started\hellojpa>jant setup 

Once the sample code has been built and the database has been set up, the packaged module is ready to be deployed.

10.2.3. Deployment

A packaged EJB application can be deployed using WebAdmin or console.

Deploying an EJB Application in WebAdmin

This section describes how to deploy an EJB application in WebAdmin.

  1. Log in to WebAdmin using a Web browser.

  2. Click [Applications] from the left pane to go to the application list page.

    Click [Install] on the Deployed Applications page.

    [Figure 10.7] List of Applications Installed on DAS

    List of Applications Installed on DAS


  3. Enter the ID in 'Id' field of the Install page. Click [Choose Files] next to the Path option, select the newly created application, and then click [OK].

    The path of the new application is 'JEUS_HOME/samples/getting_started/hellojpa/dist'.

    [Figure 10.8] Select an Installation Target

    Select an Installation Target


  4. The list of applications deployed on DAS is shown on the Deployed Applications page. Click [Deploy] to deploy the application to an MS.

    [Figure 10.9] List of Installed Applications

    List of Installed Applications


  5. Select a server to deploy the application to from the Target Server list, and then click [OK]. Although both DAS and MS can be selected, it is recommended to deploy the application to an MS.

    [Figure 10.10] HelloJPA Deployment Options

    HelloJPA Deployment Options


  6. The following message is displayed after the web application has been deployed successfully.

    [Figure 10.11] HelloJPA Deployment Successful Message

    HelloJPA Deployment Successful Message


Note

As discussed in "8.4. Adding Data Sources", deployment will fail if the data source is not configured correctly, such as having an incorrect password or IP address.

Deploying an EJB Application Using a Console Tool

This section describes how to deploy an EJB application in the console.

  1. Log in to JEUS as jeusadmin.

    jeusadmin –u administrator –p <password>
  2. Install the application on DAS.

    [DAS]jeus_domain.adminServer>install-application -id hellojpa C:\TmaxSoft\JEUS8\samples\getting_started\hellojpa\dist\hellojpa.ear
    Successfully installed application[hellojpa].
  3. Deploy the application to an MS (Server 1).

    [DAS]jeus_domain.adminServer>deploy hellojpa -servers server1
    Succeeded to deploy the application : hellojpa
  4. Verify that the application has been deployed successfully.

10.2.4. Execution Result

This section describes how to execute and test the deployed application.

To execute HelloJPA:

  1. Open a browser window and enter the following URL into the address bar.

    http://localhost:8088/hellojpa/

    [Figure 10.12] HelloJPA Client Page

    HelloJPA Client Page


  2. Click [Invoke ProductManager Client] to execute the HelloJPA servlet that invokes the EJB. The following result will appear.

    [Figure 10.13] HelloJPA Servlet Execution Result

    HelloJPA Servlet Execution Result