Using EJB

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

1. Session Bean Example

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

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 of Stateless Session Bean: <Hello.java>
    package helloejb;
    
    import jakarta.ejb.Remote;
    
    @Remote
    public interface Hello {
        String sayHello();
    }
  • Bean Class

    Example of Stateless Session Bean: <HelloBean.java>
    package helloejb;
    
    import jakarta.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 Servlet Client

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

Example of Servlet Client: <HelloClient.java>
package helloejb;

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

import jakarta.servlet.*;
import jakarta.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

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'.

1.3. Deployment

A packaged EJB application can be deployed using the console.

Using the console tool

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

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

  2. Log in to JEUS as jeusadmin.

    jeusadmin –u jeus –p  <password>
  3. Install the application on MASTER.

    [MASTER]domain1.adminServer>install-application -id helloejb C:\TmaxSoft\JEUS\samples\getting_started\helloejb\dist\helloejb.ear
    Successfully installed application[helloejb].
  4. Deploy the application to an MS (Server 1).

    [MASTER]domain1.adminServer>deploy helloejb -servers server1
    Succeeded to deploy the application : helloejb

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 webmanager jarmodule5
    HelloEJB Client Page
  2. Click [Invoke HelloEJB Client] to execute the HelloClient servlet that invokes the EJB. The following result will appear.

    figure webmanager jarmodule6
    HelloEJB Servlet Execution Result

2. Example of Java Persistence API

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

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 of Java Persistence API: <Product.java>
    package hellojpa;
    
    import java.io.Serializable;
    import jakarta.persistence.Entity;
    import jakarta.persistence.Id;
    import jakarta.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 of Java Persistence API: <ProductManager.java>
    package hellojpa;
    
    import java.util.Collection;
    import jakarta.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 of Java Persistence API: <ProductManagerBean.java>
    package hellojpa;
    
    import java.util.Collection;
    import jakarta.ejb.Stateless;
    import jakarta.persistence.EntityManager;
    import jakarta.persistence.PersistenceContext;
    import jakarta.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
Example of Servlet Client

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

Example of Servlet Client: <ProductManagerClient.java>
package hellojpa;

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

import jakarta.servlet.*;
import jakarta.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

2.2. Compilation

The following are the steps for compiling the sample code using jant. When it is successfully built and the database configuration is completed, the packaged module can be deployed.

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

    C:\TmaxSoft\JEUS\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 System Configuration.

    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\JEUS\samples\getting_started\hellojpa>jant setup 

2.3. Deployment

A packaged EJB application can be deployed using the console tool.

Using the console tool

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

  1. Log in to JEUS as jeusadmin.

    jeusadmin –u jeus –p <password>
  2. Install the application on MASTER.

    [MASTER]domain1.adminServer>install-application -id hellojpa C:\TmaxSoft\JEUS\samples\getting_started\hellojpa\dist\hellojpa.ear
    Successfully installed application[hellojpa].
  3. Deploy the application to an MS (Server1).

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

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 webmanager jpamodule5
    HelloJPA Client Page
  2. Click [Invoke ProductManager Client] to execute the HelloJPA servlet that invokes the EJB. The following result will appear.

    figure image080
    HelloJPA Servlet Execution Result