Use EJB 3.0 Session Beans in Spring Beans

How-To : Using EJB 3.0 Session beans in Spring Beans

Date: 7/06/06
Author: Debu Panda

Introduction

This example application demonstrates using EJB 3.0 Session beans from Spring Beans. This sample uses a EJB 3.0 Session bean (EmployeeFacade EJB) that uses JPA to persist an entity. The EJB 3.0 Session bean is injected into a Spring bean (EmployeeFacadeServiceBean). The web module uses the Spring bean to persist the entity instance. The application uses declarative transaction with EJB 3.0. For simplicity we have used a Servlet (InsertServlet) as a controller and it uses EmployeeServiceFacadeBean .

Stateless bean example using EJB 3.0

 

The demo Session bean example uses JPA and manipulates a simple Entity class. Following is the example code of Stateless session bean.


@Stateless
public class EmployeeFacadeBean  implements EmployeeFacade {
@PersistenceContext
   private EntityManager em;

      public Employee addEmployee(String empName, double sal) {
         Employee emp = new Employee();
         emp.setName(empName);
         emp.setSal(sal);
         em.persist(emp);
         return emp;
      }

  public Employee findEmployeeByEmpNo(Long empNo){
      return em.find(Employee.class,empNo);
}

}

The entity class is a plain java class that is annotated with @Entity to mark it as an entity.

@Entity
@Table(name = "EMPLOYEES")
public class Employee implements java.io.Serializable
{
  private Long empNo;
  private String name;
  private double sal;

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  @Column(name="EMPNO")
  public Long getEmpNo()
  {
    return empNo;
  }

..

}

The entity is configured in a persistence unit named howto as defined the persistence.xml. Note that the persistence unit uses a datasource with jndi location jdbc/OracleDS .

 <persistence-unit name="howto">
<jta-data-source>jdbc/OracleDS</jta-data-source>
<properties>
<property name = "toplink.ddl-generation"
value = "create-tables"/>
<property name = "toplink.ddl-generation.output-mode" value = "database"/>
</properties>
</persistence-unit>
</persistence>

Using EJB 3.0 Stateless Session bean


EJB 3.0 are POJOs and directly be used from Spring by accessing it from JNDI. Unlike EJB 2.1 Session beans you do not require to create another business interface for your EJBs because the interfaces are already business interfaces. Also you will not require the Spring's proxy classes any more.

 

We will use the EmployeeFacade EJB from a Spring bean that is used from a Servlet. Following is the code for the Spring bean that uses EmployeeFacade EJB.

 

public class EmployeeFacadeServiceBean implements EmployeeFacadeService  {

protected EmployeeFacade employeeFacade ;
 				
//Uses setter injection    
  public void setEmployeeFacade(EmployeeFacade employeeFacade) {
     this.employeeFacade = employeeFacade;
  }


   public Employee addEmployee(String empName, Double sal){
       return (Employee) this.employeeFacade.addEmployee(empName, sal);   
   }

    public Employee findEmployeeByEmpNo(Long empNo) {
       return (Employee) this.employeeFacade.findEmployeeByEmpNo(empNo);
    }

}

The InsertServlet uses the Spring Bean (EmployeeFacadeServiceBean) .

@EJB(name="ejb/EmployeeFacade",beanInterface=oracle.ejb30.EmployeeFacade.class)
public class InsertServlet extends HttpServlet 
{

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    ..
            EmployeeFacadeServiceBean es = (EmployeeFacadeServiceBean) appContext.getBean("employeeFacadeService");
            Employee emp = es.addEmployee(name,sal);
            System.out.println("Successfully persisted an employee");

   
..
 }   
}

Wiring in Spring Configuration


The howto-ejb-service.xml packaged in the web module contains the Spring configuration. Note that the Spring Bean uses a remote business interface of EmplyeeFacade EJB and is retrieved from the ENC using the JndiObjectFactoryBean as follows:

<bean id = "employeeFacade" class = "org.springframework.jndi.JndiObjectFactoryBean">
<property name = "jndiName" value = "java:comp/env/ejb/EmployeeFacade"/>
</bean>


We use setter injection in EmployeeFacadeServiceBean to inject an instance of EmployeeFacade EJB and hence must be referenced as follows:

<bean id="employeeFacadeService" class="oracle.ejb30.EmployeeFacadeServiceBean">
<property name = "employeeFacade" ref = "employeeFacade"/>
</bean>

 

Prerequisites

What you need to know

In order to complete the example application, you should be familiar with the following:

For further information on EJB 3.0, see the following documents on OTN:

Software Requirements

This demonstration requires that the following software components are installed and configured correctly:

Notations

  • %ORACLE_HOME% - The directory where you installed the Oracle Application Server 10g 10.1.3 .1
  • %SPRING_HOME% - The directory where Spring Framework version 2.0 is installed
  • %JAVA_HOME% - The directory where your JDK is installed
  • %HOWTO_HOME% - The directory where this demo is unzipped

Building the Application

The configuration files are located in the %HOWTO_HOME%/etc directory, including deployment descriptor files such as application.xml.

Running the Application

To run the sample application on a standalone instance of Oracle Application Server 10g 10.1.3.1, follow these steps:

1. Examine the Sample File Directories

  • build - temporary directory created during the build
  • log - temporary directory holding build/deploy logs
  • etc - all necessary files to package the application
  • lib - holds the application archives that could be deployed
  • doc - the How-to document and Javadoc's
    • how-to-spring-ejb30.html - this How-to page
  • src - the source of the demo
    • ejb - contains the sample entity, Spring bean and DAO
    • web- contains application

2. Configure the Environment

Ensure the following environment variables are defined:

  • %ORACLE_HOME% - The directory where you installed OC4J.
  • %SPRING_HOME% - The directory where you installed Spring 2.0
  • %JAVA_HOME% - The directory where you installed the J2SE 5.0
  • %PATH% - includes %ORACLE_HOME% /ant/bin

Configure Data Source

This example requires the default DataSource (with jndi-location as jdbc/OracleDS)to be configured to connect to the database where you want to persist the entity. The persistence unit is configured to use automatic table creation feature of Oracle TopLink Essentials. For details see http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-extensions.html.

For OC4J, you must configure a datasource in the %ORACLE_HOME%/j2ee/home/config/data-sources.xml file and point it at the schema.

An example configuration. You can use Application Server Control to create or modify an existing DataSource.

<connection-pool name="ScottConnectionPool">
  <connection-factory factory-class="oracle.jdbc.pool.OracleDataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:thin:@localhost:1521:ORCL" >
  </connection-factory>
</connection-pool>

<managed-data-source name="OracleManagedDS"
 connection-pool-name="ScottConnectionPool"
 jndi-name="jdbc/OracleDS"
/> 

 

You can create the JDBC resources by using ANT tasks. Make sure you change the database configurations (db.host, db.sid, db.port, db.user, db.password) in ant-oracle.properties file.

Ensure $ORACLE_HOME/ant/bin is included in your PATH environment variable and then use the following command:

>ant configure-ds

3. Start the Server

Start OC4J stand alone using the following command after you make the above changes.

>%ORACLE_HOME%/bin/oc4j -start

If you are using an OracleAS managed install, start using the following command after you make the above changes.

> %ORACLE_HOME%/opmn/bin/opmnctl startall

4. Generate, Compile, and Deploy the Application

Ant 1.6.2 is shipped with OC4J and you have to set your PATH environment variable to $ORACLE_HOME/ant/bin. On some operating systems, Ant does not currently support the use of environment variables. If this is the case for your operating system, please modify the ant-oracle.xml file located in the %HOWTO_HOME% directory.

Edit ant-oracle.properties (in the demo directory) and ensure the following properties are set to the correct values, as indicated below for OC4J standalone:

  • oc4j.host: host where OC4J is running (default localhost)
  • oc4j.admin.port: RMI port number (default 23791)
  • oc4j.admin.user: admin user name (default oc4jadmin)
  • oc4j.admin.password: admin user password (default welcome)
  • oc4j.binding.module: website name where deployed web modules are bound (default http-web-site)

If you are using OracleAS managed install then you have appropriately change the following properties beside changing oc4j.admin.user and oc4j.admin.password for your managed OC4J instance in OracleAS install.

  • opmn.host: the hostname/IP where OracleAS is running (default localhost)
  • opmn.port: OPMN request port (default 6003) for the OracleAS install
  • oc4j.instance: admin user name (default oc4jadmin)

You have to uncomment appropriate deployer.uri in the ant-oracle.properties based on your environment i.e. a single instance OC4J or a clustered OC4J instance/group managed by OPMN.

To build the application, type the following command from the %HOWTO_HOME% directory:

>ant

You should now have the newly created springejb3.ear in your %HOWTO_HOME%/lib directory.

This command will attempt to deploy the application archive if the build is successful. It will first test whether OC4J is running before attempting the deployment operation.

Note that you can also deploy the application separately . Ensure the %ORACLE_HOME% environment variable is defined, and from the %HOWTO_HOME% directory, type the command:

>ant deploy

5. Run the Application

Run the sample by providing invoking the following URL from your favorite browser:

http://localhost:8888/springejb3

In this page, enter employee no, Name and Salary and then click on Add Employee button.

The InsertServlet will be invoked that will try to persist the employee. The InsertServlet invokes addEmployee method EmployeeFacade. The EmployeeFacade bean uses the EmployeeServiceBean (Spring managed Bean) that in turns uses Spring JpaTemplate to persist the entity instance.

You will be redirected to a success page if your record was inserted successfully. You can also check the database table to ensure the record was created.

Summary

In this document, you should have learned how to:

  • Access an EJB 3.0 Session Bean from Spring bean
  • Deploy and execute a sample application using EJB 3.0 Session bean in Spring with Oracle Application Server 10g 10.1.3.1

E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy