Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

The following article provides concept-rich documentation on how to use JNDI to access connection pools for data sources, Java Messaging Services (JMS), mail sessions, and URL connections: Apache Geronimo JNDI naming and Java resource connection pools, Part 1: Data source connections. URL: http://www-128.ibm.com/developerworks/opensource/library/os-ag-jndi1Image Removed

However, the mentioned article is written for Geronimo 1.x. This sample tutorial will demonstrate something similar but using EJB 3.0.

...

No Format
borderStylesolid
|-CustomerService-ear-2.0-SNAPSHOT.ear
    |-CustomerService-ejb-2.0-SNAPHOSTSNAPSHOT.jar
        |-META-INF
            |-persistence.xml
            |-openejb-jar.xml
    |-CustomerService-war-2.0-SNAPSHOT.war
        |-WEB-INF
            |-web.xml
            |-geronimo-web.xml
    |-META-INF
        |-application.xml
        |-geronimo.application.xml

...

Code Block
xml
xml
borderStylesolid
titleopenejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>

<openejb-jar xmlns="http://www.openejb.org/xml/ns/openejb-jar-2.1"
             xmlns:naming="http://geronimo.apache.org/xml/ns/naming-1.1"
             xmlns:security="http://geronimo.apache.org/xml/ns/security-1.1"
             xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2">
   <dep:environment>
      <dep:moduleId>
         <dep:groupId>default<groupId>${pom.groupId}</dep:groupId>
         <dep:artifactId>ProcessCustomerSession<artifactId>${pom.artifactId}</dep:artifactId>
         <dep:version>1.0<version>${version}</dep:version>
         <dep:type>jar</dep:type>
      </dep:moduleId>

      <dep:dependencies>
      </dep:dependencies>
      <dep:hidden-classes/>
      <dep:non-overridable-classes/>
   </dep:environment>
</openejb-jar>

...

Code Block
xml
xml
borderStylesolid
titlegeronimo-application.xml
<application xmlns="http://geronimo.apache.org/xml/ns/j2ee/application-1.1">
   <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
      <dep:moduleId>
         <dep:groupId>default<groupId>${pom.groupId}</dep:groupId>
         <dep:artifactId>CustomerService<artifactId>${pom.artifactId}</dep:artifactId>
         <dep:version>1.0<version>${version}</dep:version>
         <dep:type>ear</dep:type>
      </dep:moduleId>

      <dep:dependencies/>
      <dep:hidden-classes/>
      <dep:non-overridable-classes/>
   </dep:environment>
   
   <module>
       <connector>tranql-connector-ra-1.3.rar</connector>
       <alt-dd>CustomerServicePool.xml</alt-dd>
   </module>
   
</application>

...

Code Block
xml
xml
borderStylesolid
titleapplication.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" version="5">
  <description>Geronimo Sample EAR for CustomerService</description>
  <display-name>Geronimo Sample EAR for CustomerService</display-name>
  <module>
    <ejb>CustomerService-ejb-2.0-SNAPSHOT.jar</ejb>
  </module>
  <module>
    <web>
      <web-uri>CustomerService-war-2.0-SNAPSHOT.war</web-uri>
      <context-root>/CustomerService<service</context-root>
    </web>
  </module>
  <module>
    <connector>tranql-connector-ra-1.3.rar</connector>
  </module>
</application>

...

Code Block
java
java
borderStylesolid
titleCustomerServiceJavaBean.java
// CustomerServiceJavaBean.java

package com.service.customer.web;

import com.service.customer.ejb.Customer;
import com.service.customer.ejb.ProcessCustomerSessionLocal;

import java.util.Locale;
import java.util.ResourceBundle;
import java.util.List;
import javax.naming.InitialContext;


public class CustomerServiceJavaBean
{
   private ProcessCustomerSessionLocal process = null;
   private ResourceBundle      bundle = null;

   private Stringpublic CustomerServiceJavaBean()
   {
           JNDI_PROCESS_EJBInitialContext initial = null;

   private String   bundle   action = ResourceBundle.getBundle("customer", Locale.getDefault(), CustomerServiceJavaBean.class.getClassLoader());
   private String   String jndiName  customerID = bundle.getString("jndi.process.ejb");

   private String  try
    fullName = "";{
   private    String  initial = new  emailAddressInitialContext();
		 process = ""(ProcessCustomerSessionLocal) initial.lookup(jndiName.trim());
   private String      interests = "";


   public CustomerServiceJavaBean()System.out.println("Successful looking up: '" + jndiName.trim() + "'");
   {
   } // end InitialContexttry

 initial = null;

   catch (Exception e)
 bundle  = ResourceBundle.getBundle("customer", Locale.getDefault(), CustomerServiceJavaBean.class.getClassLoader()); {
      JNDI_PROCESS_EJB  = bundlee.getString("jndi.process.ejb"printStackTrace();

      try} // end catch
   } // end {CustomerServiceJavaBean


   public List<Customer> getAllCustomers()
   {
 initial   = new InitialContext();
	 process = (ProcessCustomerSessionLocal) initial.lookup(JNDI_PROCESS_EJB.trim());
 List<Customer> customerList = null;

      try
   System.out.println("Successful looking up: '" + JNDI_PROCESS_EJB.trim() + "'") {
         customerList = process.findAllCustomers();
      } // end try

      catch (Exception e)
      {
         e.printStackTrace();
      } // end catch
   } // end CustomerServiceJavaBean


   public List<Customer> getAllCustomers()
 return  {customerList;
   } // end List<Customer> customerList = null;

      try
      {
         customerList = process.findAllCustomers();
      } // end try

      catch (Exception e)
      {
         customerList = null;
         e.printStackTrace();
      } // end catch

      return customerList;
   } // end getAllCustomerss
} // end CustomerServiceJavaBean

ProcessCustomerSessionBean.java implements ProcessCustomerSessionLocal by grabbing an EntityManagerFactory by making use of the persistence.xml. It grabs it by using the @PersistenceUnit annotation. Since there is only one persistence unit defined in persistence.xml, we do not need to specify any additional parameters in the annotation.

getAllCustomerss
} // end CustomerServiceJavaBean

ProcessCustomerSessionBean.java implements ProcessCustomerSessionLocal by grabbing an EntityManagerFactory by making use of the persistence.xml. It grabs it by using the @PersistenceUnit annotation. Since there is only one persistence unit defined in persistence.xml, we do not need to specify any additional parameters in the annotation.

Code Block
java
java
borderStylesolid
titleProcessCustomerSessionBean.java

package com.service.customer.ejb;

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.persistence.PersistenceUnit;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

@Stateless
public class ProcessCustomerSessionBean implements ProcessCustomerSessionLocal {
    @PersistenceUnit
    protected EntityManagerFactory emf;

    public ProcessCustomerSessionBean() {
    
    }

    public List<Customer> findAllCustomers() {
        EntityManager em = emf.createEntityManager();
        String query = "SELECT * FROM customer";
        List<Customer> customerList =
            (List<Customer>)em.createNativeQuery(query, Customer.class).getResultList();
        em.close();
        return customerList;
    }

    public Customer findCustomer(String key) {
        EntityManager em = emf.createEntityManager();
        String
Code Block
javajava
borderStylesolid
titleProcessCustomerSessionBean.java

package com.service.customer.ejb;

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.persistence.PersistenceUnit;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

@Stateless
public class ProcessCustomerSessionBean implements ProcessCustomerSessionLocal {
    @PersistenceUnit
    protected EntityManagerFactory emf;

    public ProcessCustomerSessionBean() {
    
    }

    public List<Customer> findAllCustomers() {
        EntityManager em = emf.createEntityManager();
        String query = "SELECT * FROM customer WHERE id='"+key+"'";
        List<Customer> customerList =
            (List<Customer>)em.createNativeQuery(query, Customer.class).getResultList();
        emif(customerList.closesize();
 == 1) {
     return customerList;
    }

    publicreturn Customer findCustomer(String key) {(Customer)customerList.get(0);
        EntityManager} em = emf.createEntityManager();else {
        String query = "SELECT * FROM customer WHERE id='"+key+"'"return null;
        List<Customer> customerList =}
    }
}

ProcessCustomerSessionLocal.java defines the business methods that is associated with this bean.

Code Block
java
java
borderStylesolid
titleProcessCustomerSessionLocal.java

package com.service.customer.ejb;

import com.service.customer.ejb.Customer;

public interface ProcessCustomerSessionLocal {
    (List<Customer>)em.createNativeQuery(query, Customer.class).getResultListpublic java.util.List<Customer> findAllCustomers();

    public Customer   if(customerList.size() == 1) {
            return (Customer)customerList.get(0);
        } else {
            return null;
        }
    }
}

ProcessCustomerSessionLocal.java defines the business methods that is associated with this bean.

findCustomer(String key);
}

Customer.java is the entity bean that represents the Customer table in the database. By using @Entity, @Table(name = "customer"), and @Id it tells OpenEJB that this is an entity bean, which is representative of the table "customer" and has "customerId" as the primary key. By using these annotations no other configuration is needed inside openejb-jar.xml (no ejb-jar.xml is needed at all).

Code Block
java
java
borderStylesolid
titleCustomer.java

package com
Code Block
javajava
borderStylesolid
titleProcessCustomerSessionLocal.java

package com.service.customer.ejb;

import com.service.customer.ejb.Customer;

public interface ProcessCustomerSessionLocal {
    public import java.util.List<Customer> findAllCustomers();

    public Customer findCustomer(String key);
}

Customer.java is the entity bean that represents the Customer table in the database. By using @Entity, @Table(name = "customer"), and @Id it tells OpenEJB that this is an entity bean, which is representative of the table "customer" and has "customerId" as the primary key. By using these annotations no other configuration is needed inside openejb-jar.xml (no ejb-jar.xml is needed at all).

Code Block
javajava
borderStylesolid
titleCustomer.java

package com.service.customer.ejb;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private String customerId;
    private String fullName;
    private String emailAddress;
    private String interests;

    public Customer() {

    }

    public Customer(String customerId, String fullName, String emailAddress,
                    io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private String customerId;
    private String fullName;
    private String emailAddress;
    private String interests;

    public Customer() {

    }

    public Customer(String customerId, String fullName, String emailAddress,
                    String interests) {
        this.customerId = customerId;
        this.fullName = fullName;
        this.emailAddress = emailAddress;
        this.interests = interests;
    }

    @Id
    public String getCustomerId() {
        return customerId;
    }

    public String getFullName() {
        return fullName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public String getInterests() {
        return interests;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public void setInterests(String interests) {
        this.interests = interests;
    }
} // end Customer

Customer Service Database

The database that will be used to demonstrate this application is the built-in Derby database. The name of the database will be CustomerDB and it consists of one table:

Table Name

Fields

CUSTOMER

customerId (PRIMARY KEY)
fullname
emailaddress
interests

The CUSTOMER table stores information about one customer.

Tools used

The tools used for developing and building the Banking applications are:

Apache Derby

Apache Derby, an Apache DB subproject, is a relational database implemented in Java. Its footprint is so small you can easily embed it in any Java-based solution. In addition to its embedded framework, Derby supports a more familiar client/server framework with the Derby Network Server.
http://db.apache.org/derby/index.html

Apache Maven 2

Maven is a popular open source build tool for enterprise Java projects, designed to take much of the hard work out of the build process. Maven uses a declarative approach, where the project structure and contents are described, rather than the task-based approach used in Ant or in traditional make files, for example. This helps enforce company-wide development standards and reduces the time needed to write and maintain build scripts. The declarative, lifecycle-based approach used by Maven 1 is, for many, a radical departure from more traditional build techniques, and Maven 2 goes even further in this regard. Maven 2 can be download from the following URL:
http://maven.apache.org

Configuring, Building and Deploying the Sample Application

Download the CustomerService application from the following link:
CustomerService

After decompressing the given file, the CustomerService directory will be created.

Configuring

Configuration of the application consists of creating the database and defining the connection pool to access it.

Creating and Populating Database

...

 end Customer

Customer Service Database

The database that will be used to demonstrate this application is the built-in Derby database. The name of the database will be CustomerDB and it consists of one table:

Table Name

Fields

CUSTOMER

customerId (PRIMARY KEY)
fullname
emailaddress
interests

The CUSTOMER table stores information about one customer.

Tools used

The tools used for developing and building the Banking applications are:

Apache Derby

Apache Derby, an Apache DB subproject, is a relational database implemented in Java. Its footprint is so small you can easily embed it in any Java-based solution. In addition to its embedded framework, Derby supports a more familiar client/server framework with the Derby Network Server.
http://db.apache.org/derby/index.html

Apache Maven 2

Maven is a popular open source build tool for enterprise Java projects, designed to take much of the hard work out of the build process. Maven uses a declarative approach, where the project structure and contents are described, rather than the task-based approach used in Ant or in traditional make files, for example. This helps enforce company-wide development standards and reduces the time needed to write and maintain build scripts. The declarative, lifecycle-based approach used by Maven 1 is, for many, a radical departure from more traditional build techniques, and Maven 2 goes even further in this regard. Maven 2 can be download from the following URL:
http://maven.apache.org

Configuring, Building and Deploying the Sample Application

Download the CustomerService application from the following link:
CustomerService

After decompressing the given file, the CustomerService directory will be created.

Source Code

You can checkout the source code of this sample from SVN:

svn checkout http://svn.apache.org/repos/asf/geronimo/samples/trunk/samples/CustomerService

Configuring

Configuration of the application consists of creating the database and defining the connection pool to access it.

Creating and Populating Database

After starting Apache Geronimo log into the console and follow the given steps to create CustomerDB.

No Format
borderStylesolid
titleCustomerService.sql

create table customer (
   customerid varchar(10) primary key,
   fullname varchar(30),
   emailaddress varchar(30),
   interests varchar(100)
);

insert into customer values ('A100','John Doe10','Doe10@work.com','Java,Open Source, Computer Graphics');
insert into customer values ('b100','Jane Doe20','Doe20@home.net','Budget Travel, New Zealand, Martial Arts');
  1. Select DB Manager link from the Console Navigation in the left.
  2. Give the database name as CustomerDB and click Create button.
  3. Select CustomerDB to the Use DB field.
  4. Open CustomerService.sql in the CustomerService directory from a text editor.
  5. Paste the content CustomerService.sql to the SQL Commands text area and press Run SQL button.

...

To test the sample web application open and browse and type http://localhost:8080/serviceImage Removed. It will forward you to the index page of the application which has a direct link to view the Customers.
Image Added