EJB V3.0 database persistence with Eclipse

Learn to create EJB V3.0 entity beans with the Eclipse-WebSphere7-DB2 database

EJB V3.0 provides a robust toolset for data persistence in Java™ technology. Using EJBs doesn't have to be hard. Learn how to access these features in an Eclipse environment and have stronger integration of your applications with the data available. Trial versions of IBM® WebSphere® Application Server and DB2® were used for the examples, but the techniques discussed are transferable to the Community editions of WebSphere Application Server and DB2. Apache OpenEJB is included in IBM WebSphere Application Server CE.

Introduction

One thing that has changed in the application development world is the availability of data. There is all kinds of data from all kinds of resources. On one hand, this makes applications richer than ever. On the other hand, all of this data can be a reall mess to deal with. It becomes even more complicated if you need to persist data, rather than just read it.

In a Java environment, EJBs have emerged as a way to reliably persist while maintaining a good level of maintainability and appropriate segregation of roles. EJB V3.0 has continued that evolution, bringing more tools and options. Working with EJBs doesn't have to be hard. With Eclipse and some basic concepts, you can harness their power in your applications.

EJB V3.0

EJB V3.0 has simplified the development of EJBs with an annotations-based API in which remote/local interfaces, home/local home interfaces, and deployment descriptors are not required, though may be used. Developing Entity EJBs requires a Java IDE, an application server, and a relational database. WebSphere V6.x requires the WebSphere Application Server V6.1 Feature Pack to create EJB V3.0 entity beans. WebSphere V7 has built-in support for EJB V3.0. The Eclipse IDE is the most commonly used open source Java IDE. In this article, we'll develop an EJB V3.0 entity bean using the Eclipse-IBM WebSphere 7-IBM DB2 9.5 combination.

The EJB V3.0 specification in WebSphere is backed with Java Persistence API (JPA) for persistence. JPA is further based on other persistence technologies, such as Hibernate, JDO, and TopLink. JPA is a POJO persistence API for object-relational mapping and makes use of metadata annotations to define mapping between Java objects and a relational database. JPA supports a SQL-like language for static and dynamic queries. JPA is integrated into the JSR 220: Enterprise JavaBeans V3.0 specification.

Trial versions of WebSphere application server and DB2 database were used, but the techniques discussed are transferable to the Community editions of WebSphere Application Server and DB2. The trial version of WebSphere Application Server includes free support. Support for the Community edition of WebSphere Application Server is also available.


Preliminary setup

  1. Download and install WebSphere Application Server V7 (see Resources).
  2. Download and install Eclipse IDE for Java EE Developers (see Resources).
  3. Download and install DB2 V9.5 (see Resources).
  4. Create database instance SAMPLE in DB2.

Configuring WebSphere with DB2

Start the WebSphere Application Server. At the First Steps Console, select Start the server. The WebSphere server is initiated, as shown in Figure 1.

Figure 1. Starting WebSphere V7 Application Server
Screenshot showing the console messages as WebSphere Application Server V7 starts

Next, start the Administrative Console/Integrated Solutions Console by selecting the Administrative Console link. In the Integrated Solution Console window, select Resources > JDBC > JDBC > New in the JDBC providers table, as shown in Figure 2.

Figure 2. Creating a new JDBC provider
Screenshot shows the WebSphere Application Server Administrative Console as the JDBC providers are configured

In the Create a new JDBC Provider window, select Database > DB2, Provider > DB2 Universal JDBC Driver Provider, and Implementation > Connection pool datasource, then click Next, as shown in Figure 3.

Figure 3. Setting configuration values
Screenshot shows the configuration of the specific JDBC data resources

The Summary page lists the summary of the JDBC provider configuration. Select Finish. A new JDBC provider is added to the JDBC providers table. Select the new JDBC provider, and click Save to store the JDBC provider to the master configuration, as shown in Figure 4.

Figure 4. New JDBC provider
Screenshot shows the successfully configured JDBC provider in the Administrative Console

Prior to configuring a data source, a J2EE connector authentication data entry is needed. J2EE connector authentication data entries are used by JDBC data sources to log in to a database. Select the Security > Global security node in the Integrated Solutions Console. Next, select the Java Authentication and Authorization Service > J2C authentication data link in the Authentication subheader, as shown in Figure 5.

Figure 5. Creating J2C authentication data
Screenshot shows the console as authentication settings are configured

In the table of user identities and passwords, click New. In the new header, specify a user alias in the Alias field, a User Id, which is the login ID for the DB2 database, and the password to login to the DB2 database, as shown in Figure 6.

Figure 6. Specifying J2C authentication data properties
Screenshot shows the entry of the name and password for database authentication

Click Save to store the J2C authentication data entry to the master configuration. A DB2 database login alias is added to the J2C authentication data table, as shown in Figure 7.

Figure 7. New J2C authentication data
Screensthot shows the successful configuration of the autentication data

To configure a JDBC data source, select the JDBC provider previously configured. In the DB2 Universal JDBC Provider header, click the Datasources link, as shown in Figure 8.

Figure 8. Data sources
Screenshot shows the WebSphere Application Server V7 Administrative Console as the JDBC data sources are defined

Click New in the Data sources table to create a new data source. Specify a JNDI name and click Next, as shown in Figure 9. The JNDI name shall be used in the persistence.xml file for the EJB V3.0 entity bean, which will be created later.

Figure 9. Creating a data source
Screenshot shows the WebSphere Application Server V7 Administrative Console as an individual datasource is configured

Specify the data source-specific properties for the data source. Select Driver Type > 4, Database Name > SAMPLE, Server Name > localhost, and Port Number > 50000. Click Next, as shown in Figure 10.

Figure 10. Specifying data-source properties
Screenshot shows the WebSphere Application Server V7 Administrative Console as the data-source properties are defined

To select the J2C authentication data for the data source, choose the authentication alias created earlier. Click Next, as shown in Figure 11.

Figure 11. Setting the security alias
Screenshot shows the WebSphere Application Server V7 Administrative Console as the security alias is defined for the database

In the Summary page for the data source, select Finish. A new data source is added to the table. Click Save to store the data source to the master configuration. Select Data Source > Test Connection in the table. The data source connection test will indicate whether the test is successful, as shown in Figure 12.

Figure 12. Testing the data-source connection
Screenshot shows the WebSphere Application Server V7 Administrative Console as the connectivity to the database is tested

Creating a DB2 database table

Access the DB2 database from a command-line tool, such as the Command Editor or the Command Line Processor. To create a database table in the default sample database SAMPLE, run the following SQL script. This creates a Catalog table for the EJB V3.0 entity bean.

CREATE TABLE Catalog (id INT PRIMARY KEY NOT NULL, 
journal VARCHAR(100), publisher VARCHAR(100), date VARCHAR(100), 
title VARCHAR(100), author VARCHAR(100));

Creating an EJB V3.0 project in Eclipse

  1. In Eclipse IDE, select File > New > Project.
  2. In the New Project window, select EJB > EJB Project > Next.
  3. In the New EJB Project window, specify a project name (EJB3EntityBean, for example). Select EJB Module Version > 3.0 > Next.
  4. In the EJB Module window, select the default Source Folder > ejbModule > Finish.
  5. Next, add an entity bean Java class to the EJB V3.0 project. Select File > New > Other and in the New window, select Java > Class > Next.
  6. In the New Java Class window, the Source folder is EJB3EntityBean/ejbModule by default. Specify a package name (com.ejb3.websphere, for example) and a class name (Catalog), then click Finish.
  7. An entity bean Java class is added to the EJB V3.0 project. WebSphere V7 requires JDK V6. If not already installed, install JDK V6 (see Resources). Right-click on EJB 3.0 > Properties and select the Java Build Path node. Add the JRE System Library [jre6], as well as the J2EE V5 JAR, which is included in WebSphere V7. Create a library EJB3 and add j2ee.jar to the library, as shown in Figure 13.
Figure 13. Libraries in the Java Build Path
Screenshot shows the Eclipse configuaration where the libraries in the Java Build Path are defined

Add the source folder ejbModule to the Java Build Path, as shown in Figure 14.

Figure 14. Source folder in Java Build Path
Screenshot shows the Eclipse Java Build Path configuration as the folder ejbModule is added

Similar to adding the Catalog.java bean class, add Java classes CatalogTestBean.java (the session bean), CatalogTestLocal.java (local business interface), and CatalogTestRemote.java (remote business interface). An EJB V3.0 entity bean is required to have a persistence.xml configuration file in the META-INF directory.

  1. In the Project Explorer, select META-INF > File > New > Other.
  2. In the New window, select XML > XML > Next.
  3. In the New XML File window, select the ejbModule > META-INF folder. Specify File Name > persistence.xml > Finish. A persistence.xml file is added to the META-INF folder.
  4. Create a build.xml script in the EJB V3.0 project with File > New > Other > XML > XML. Create a META-INF folder in the project folder, and add application.xml to the folder.
  5. Create a webModule folder to the project folder for a JSP client to the entity EJB, and add EJB3Client.jsp to the folder.
  6. Add a WEB-INF folder to the webModule folder, and add a web.xml file to the WEB-INF folder. The directory structure of the EJB V3.0 project is shown in Figure 15.
Figure 15. Directory structure of EJB V3.0 project
Screenshot of the project in Eclipse showing the file heirarchy

Creating an EJB V3.0 entity bean

Unlike EJB V2.0, in EJB V3.0 entity beans are Plain Old Java Objects (POJOs). Entity-bean mappings are defined using annotations, which were introduced in JDK V5 and are in the javax.persistence package. A POJO class annotated with the @Entity annotation is an entity bean. The schema and table for the entity bean mapping is set at the class level using the @Table annotation. If the @Table annotation is not specified, the default table name is the entity bean class name. We shall create an entity bean Catalog that is mapped to Catalog table.

@Entity
@Table(name="Catalog")
public class Catalog implements Serializable {
...
}

If an entity bean that has caching enabled is persisted to a database via the entity manager, the entity bean is serialized by caches. Therefore, an entity bean is recommended to implement the java.io.Serializable interface. In the entity-bean class, specify the POJO properties. Also specify the serialVersionUID, which is used by the serialization runtime to associate a version number with the serializable class. Add the getter and setter methods for the entity bean properties. Specify the identifier property with the @Id annotation. There are additional EJB V3.0 annotations, which may be specified in an entity bean (see Resources). The Catalog entity bean is shown in Listing 1.

Listing 1. Entity-bean class Catalog.java
import java.io.Serializable;
import javax.persistence.*;


@Entity
@Table(name="Catalog")
public class Catalog implements Serializable {
	private static final long serialVersionUID = 7422574264557894633L;
	private long id;
	private String journal;
            private String publisher;
            private String date;
	private String title;
            private String author;

    public Catalog(){ super();}

    public Catalog(Integer id, String journal, String publisher, String date, 
               String title, String author){
    super();
    this.id=id;
    this.journal=journal;
    this.publisher=publisher;
    this.date=date;
    this.title=title;
    this.author=author;
    }

	@Id
		public long getId() {
		return id;
	}

	
	public void setId(long id) {
		this.id = id;
	}

        public String getJournal() {
		return journal;
	}

	
	public void setJournal(String journal) {
		this.journal = journal;
	}

         public String getPublisher() {
		return publisher;
	}

	
	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}


           public String getDate() {
            return date;
           }
 
           public void setDate(String date) {
            this.date = date;
           }

	
	public String getTitle() {
		return title;
	}

	
	public void setTitle(String title) {
		this.title = title;
	}


        public String getAuthor() {
		return author;
	}

	
	public void setAuthor(String author) {
		this.author = author;
	}

}

Creating a persistence configuration file

The root element in the persistence.xml file is persistence. The persistence-unit is required to be named. A JDBC data source with JNDI jdbc/DB2DS in the WebSphere V7 application server was previously configured. Specify the JNDI name in the jta-data-source element in persistence.xml. The default JPA persistence provider in WebSphere Application Server V7 is a version of the Apache OpenJPA provider. Copy Listing 2 to the persistence.xml file in Eclipse.

Listing 2. Configuration file persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
        <persistence-unit name="catalog">
           <jta-data-source>jdbc/DB2DS</jta-data-source>
        </persistence-unit>
        </persistence>

A WebSphere V7 limitation is that if the schema location for the persistence.xml file is specified with the following attributes in the persistence element, an error is generated.

xmlns:xsi="http://www.w3.org/2001/XMLSchema"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"

Creating a session bean

For better performance, one of the best practices (see Resources) of developing EJBs is to access entity beans from session beans. Use a stateless session bean, which consumes lesser resources than a stateful session bean, to invoke entity-bean methods. A stateless session bean class is annotated with the @Stateless annotation. The stateless session bean class CatalogTestBean implements the CatalogTestLocal and CatalogTestRemote interfaces. Use the EntityManager API to create, find, query, and remove entity instances. Inject an EntityManager using the @PersistenceContext annotation.

@PersistenceContext
            EntityManager em;

A session bean deployed to the WebSphere server with JNDI binding Session_Bean_Class_Name has the default JNDI name binding for the local business interface as ejblocal:Session_Bean_Class_Name. For convenient access to the JNDI name from a JSP client, assign public static final variable to the local JNDI name.

public static final String LocalJNDIName = "ejblocal:"
            + CatalogTestBean.class.getSimpleName();

Next, create a test() method that returns a String invoked from a test client. Use the test() method to create and persist entity instances, query an entity instance, and delete an entity instance, all using an EntityManager object, which was injected earlier in the session bean class. Injecting an EntityManager implies that an instance of EntityManager is made available to the session bean. Create an instance of the entity bean class.

Catalog catalog = new Catalog(new Integer(1), "IBM developerWorks", "IBM", 
            "July 2006", "The Java XPath API", "Elliotte Rusty Harold");

Persist the entity instance to the database using the persist() method.

em.persist(catalog);

Similarly, persist two more entity instances. Next, create a query using the createQuery method of the EntityManager object. The string is specified as an EJB-QL query. Execute and return the result as a List using the getResultList() method. As an example, select the catalog entry corresponding to author Elliotte Rusty Harold.

List catalogEntry = em.createQuery("SELECT c from Catalog c where c.author=:name").
            setParameter("name", "Elliotte Rusty Harold").getResultList();

Create a string variable for the return value of the test method.

String retValue = "<b>A catalog entry: </b>";

Iterate over the result list to output the properties of the entity instance.

for (Iterator iter = catalogEntry.iterator(); iter.hasNext();) {
Catalog element = (Catalog) iter.next();
retValue = retValue + "<br/>" + element.getJournal() + "<br/>"+ 
element.getPublisher() + "<br/>" + element.getDate() + "<br/>"+ element.getTitle() + 
"<br/>" + element.getAuthor()+"<br/>";
}

Create and run a EJB-QL query to return all titles in the Catalog database.

List allTitles = em.createQuery("SELECT c from Catalog c").getResultList();

An entity instance may be removed using the remove() method.

em.remove(catalog2);

The corresponding database row is deleted from the Catalog table. Subsequently, create and run a query to list all the remaining entity instances mapped to the database. The session bean class CatalogTestBean is shown in Listing 3.

Listing 3. Session bean CatalogTestBean.java
	package com.ejb3.websphere;

import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class CatalogTestBean implements CatalogTestRemote, CatalogTestLocal {
	@PersistenceContext
	EntityManager em;

	public static final String LocalJNDIName = "ejblocal:"
			+ CatalogTestBean.class.getSimpleName();

	public String test() {
		Catalog catalog = new Catalog(new Integer(1), "IBM developerWorks",
				"IBM", "July 2006", "The Java XPath API",
				"Elliotte Rusty Harold");
		em.persist(catalog);
		Catalog catalog2 = new Catalog(new Integer(2), "IBM developerWorks",
		   	"IBM", "March 2009", "Use XQuery for the presentation layer",
				"Brian M. Carey");
		em.persist(catalog2);
		Catalog catalog3 = new Catalog(new Integer(3), "IBM developerWorks",
			"IBM", "April 2008", "Use XQuery from a Java environment",
				"Brett McLaughlin");
		em.persist(catalog3);

		String retValue = "<b>A catalog entry: </b>";
		List catalogEntry = em.createQuery(
			"SELECT c from Catalog c where c.author=:name").setParameter(
				"name", "Elliotte Rusty Harold").getResultList();
		for (Iterator iter = catalogEntry.iterator(); iter.hasNext();) {
		        Catalog element = (Catalog) iter.next();
		        retValue = retValue + "<br/>" + element.getJournal() + "<br/>"
				+ element.getPublisher() + "<br/>" + element.getDate()
					+ "<br/>" + element.getTitle() + "<br/>"
					+ element.getAuthor() + "<br/>";

		}

		retValue = retValue + "<b>All Titles: </b>";
		List allTitles = em.createQuery("SELECT c from Catalog c")
				.getResultList();
		for (Iterator iter = allTitles.iterator(); iter.hasNext();) {
			Catalog element = (Catalog) iter.next();
			retValue = retValue + "<br/>" + element.getTitle() + "<br/>";

		}

		em.remove(catalog2);
		retValue = retValue + "<b>All Entries after removing an entry: </b>";

		List allCatalogEntries = em.createQuery("SELECT c from Catalog c")
				.getResultList();
		for (Iterator iter = allCatalogEntries.iterator(); iter.hasNext();) {
			Catalog element = (Catalog) iter.next();
			retValue = retValue + "<br/>" + element + "<br/>";

		}
		return retValue;
	}
	}

Add a remote and a local interface for the session bean (see Listing 4).

Listing 4. Remote and local interfaces for the session bean
package com.ejb3.websphere;

import javax.ejb.Remote;

@Remote
public interface CatalogTestRemote {
	public String test();
}

package com.ejb3.websphere;

import javax.ejb.Local;

@Local
public interface CatalogTestLocal {
	public String test();
	}

Creating a test client

So far, an entity bean that contains the business logic and a session bean that is a wrapper for the entity bean have been created. Next, a test client JSP EJB3Client.jsp is created in which the test() of the session bean is run. To create an instance of CatalogTestLocal using JNDI lookup, first create an IntialContext object. Obtain a CatalogTestLocal instance using JNDI lookup in the session bean.

InitialContext context = new InitialContext();
CatalogTestLocal beanLocal = (CatalogTestLocal) 
context.lookup(CatalogTestBean.LocalJNDIName);

Invoke the test() method of the session bean and output the return value.

String catalog=beanLocal.test();
<%=catalog  %>

The test client JSP EJB3Client.jsp is shown in Listing 5.

Listing 5. EJB3Client.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.ejb3.websphere.*, javax.naming.*" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>EJB3 Client</title>
</head>
<body>
<% InitialContext context = new InitialContext();
CatalogTestLocal beanLocal = (CatalogTestLocal) 
context.lookup(CatalogTestBean.LocalJNDIName);
String catalog=beanLocal.test();
%>
<%=catalog  %>
</body>
</html>

The WEB-INF/web.xml file specifies the Web deployment descriptor. As no web configuration is specified, copy the following listing to web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
  
  </web-app>

Create an application.xml deployment descriptor for the EJB and Web modules. Copy Listing 6 to application.xml.

Listing 6. application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" version="5"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  http://java.sun.com/xml/ns/javaee/application_5.xsd">
  <display-name></display-name>
  <description></description>
  <module>
   <ejb>ejb3.jar</ejb>
  </module>
  <module>
    <web>
      <web-uri>websphere.war</web-uri>        
     <context-root>websphere</context-root>
    </web>
  </module>
  </application>

Deploying the entity bean to WebSphere

All the classes and configuration files have been completed to create an EJB V3.0 entity bean. Next, compile the classes to create an EJB JAR file, a WAR file, and an EAR file, and deploy the EAR file to the WebSphere server. Use a build.xml script to compile the EJB classes, create a EJB EAR file, and deploy the EJB EAR file to WebSphere. For an introduction to Apache Ant, refer the Apache Ant User Manual (see Resources). In the build script, specify properties for the various directory paths used in the script, such as the WebSphere server directory, the build directory, and the WebSphere deploy directory. Specify the classpath of the various JAR files required for compiling the EJB classes. Specify targets discussed in Table 1.

Table 1. Targets in build.xml
TargetDescription
prepareCreates the build directory and a directory for the compiled classes
compileCompiles the EJB classes
jarCreates a EJB JAR file
warCreates a WAR file
assemble-appCreates an EAR file
deployDeploys the EAR file to WebSphere server. The WebSphere deploy directory is C:\Program Files\IBM\WebSphere\AppServer\installableApps
cleanDeletes the JAR, WAR, and EAR files

The build.xml script is shown in Listing 7.

Listing 7. build.xml
	<?xml version="1.0" encoding="UTF-8"?>

<!--
		WebSphere build file
	-->
<project name="ejb3" default="deploy" basedir=".">
	<property environment="env" />
	<property name="src.dir" value="${basedir}/ejbModule" />
	<property name="src.resources" value="${basedir}/ejbModule" />
	<property name="websphere.home" value="C:\Program Files\IBM\WebSphere" />
	<property name="websphere.server" value="C:\Program Files\IBM\WebSphere\
        AppServer"/>
	<property name="build.dir" value="${basedir}/build" />
	<property name="build.classes.dir" value="${build.dir}/classes" />
	<property name="deploy.dir" value="${websphere.server}/installableApps" />
	<path id="classpath">
		<fileset dir="${websphere.server}/java/lib">
			<include name="*.jar" />
		</fileset>
		<fileset dir="${websphere.server}/lib">
			<include name="*.jar" />
		</fileset>
		<pathelement location="${build.classes.dir}" />
	</path>
	<property name="build.classpath" refid="classpath" />
	<target name="prepare">
		<mkdir dir="${build.dir}" />
		<mkdir dir="${build.classes.dir}" />
	</target>
	<target name="compile" depends="prepare">
		<javac srcdir="${src.dir}" destdir="${build.classes.dir}" 
               debug="on" deprecation="on" optimize="off" includes="**">
			<classpath refid="classpath" />
		</javac>
	</target>
	<target name="jar" depends="compile">
		<jar jarfile="${build.dir}/${ant.project.name}.jar">
			<fileset dir="${build.classes.dir}">
				<include name="**/*.class" />
			</fileset>
			<fileset dir="${src.resources}/">
				<include name="META-INF/persistence.xml" />
			</fileset>
		</jar>
	</target>
	<target name="war" depends="jar">
		<war warfile="${build.dir}/websphere.war">
			<fileset dir="webModule">
				<include name="*.jsp" />
			</fileset>
			<fileset dir="webModule">
				<include name="WEB-INF/web.xml" />
			</fileset>
		</war>
	</target>
	<target name="assemble-app" depends="war">
		<jar jarfile="${build.dir}/${ant.project.name}.ear">
			<metainf dir="META-INF">
				<include name="application.xml" />
			</metainf>
			<fileset dir="${build.dir}" includes="*.jar,*.war" />
		</jar>
	</target>
	<target name="deploy" depends="assemble-app">
		<copy file="${build.dir}/${ant.project.name}.ear" todir="${deploy.dir}" />
	</target>
	<target name="clean">
		<delete file="${build.dir}/${ant.project.name}.ear" />
		<delete file="${build.dir}/${ant.project.name}.jar" />
		<delete file="${build.dir}/websphere.war" />
	</target>
	</project>

Run the build script in Eclipse. In Package Explorer, right-click build.xml > Run As > Ant Build, as shown in Figure 16.

Figure 16. Running build.xml
Screenshot shows the context menu in Eclipse opened to 'Run As' with options

The default build target in the build script is deploy, with each target having a dependence on the preceding one. The prepare, compile, jar, war, assemble-app and deploy targets are run, and the EAR file ejb3.ear is deployed to the WebSphere server, as shown in Figure 17.

Figure 17. Running build.xml
Screenshot in Eclips shows the Ant build executing

Installing EJB V3.0 in the WebSphere Application Server

In the Administrative Console, click Applications > New Application. In the New Application header, click New Enterprise Application. Specify the path to the ejb3.ear file and click Next, as shown in Figure 18.

Figure 18. Specifying EAR file to install
Screenshot shows the EAR file being configured for deployment in the WebSphere Application Server adminsitration console

For the entry "How do you want to install the application," select Detailed > Next. For the entry "Select installation options header," click the checkboxes Precompile JavaServer Pages files and Deploy enterprise beans. Specify the Directory to install application as "C:\Program Files\IBM\WebSphere\AppServer\profiles\AppSrv01\installedApps\dvohra09-PCNode01Cell" (for Windows) and click Next, as shown in Figure 19. The scope directory of the installation path may be different from the example.

Figure 19. Specifying install options
Screenshot showing selection of the installation options to deploy the application

Select the default settings in the "Clusters and server" header and click Next. Select the default settings in "Provide options to compile JSPs" and click Next. In the "Provide options to perform the EJB deploy" header, select Database > 9.5, JDK compilation level > 6.0, and Database access > JDBC> Next, as shown in Figure 20.

Figure 20. Specifying EJB deploy options
Screenshot shows the EJB deployment options for deploying the application

In the "Provide JSP reloading options for Web module" header, select the default settings and click Next. In the "Map shared libraries" header, select the default settings and click Next. In the "Map shared library relationships" header, select the default settings and click Next. In the Provide "JNDI names for beans" header, select JNDI name for all interfaces and specify the Target Resource JNDI name, as shown in Figure 21, then click Next.

Figure 21. Specifying session bean JNDI name
Screenshot shows the JNDI configuration for the application deployment

In the "Bind EJB Business" header, select the default settings and click Next. In the "Map virtual hosts for Web modules" header, select the websphere.war WAR file, select the "default_host" Virtual Host, and click Apply. Click Next. In the Map context roots for Web modules header, the context root for the websphere.war" Web module is specified as "websphere." Click Next. In the "Metadata for modules header, select the default settings and click Next. In the "Summary" page, click Finish. The ejb3.ear EAR file is installed and the ejb3.jar EJB JAR files are deployed, as shown in Figure 22. Click Save to store the master configuration changes.

Figure 22. EAR file installed
Screenshot shows successful installation of the EAR file

Click Start to initiailize the EJB3 application, which is installed and started as shown in Figure 23.

Figure 23. EAR application started
Screenshot shows the EJB3 application running in the WebSphere Application Server V7 Administrative Console

To run the JSP client for the EJB V3.0 entity bean, invoke the JSP with the URL http://localhost:9080/websphere/Catalog.jsp. The test() method of the session bean is invoked. Three entity bean instances are created and persisted to DB2. As shown in the client JSP output in Figure 24, the entity-bean property values for the entity instance corresponding to author Elliotte Rusty Harold are listed. The titles of all the entity instances are listed. An entity instance is removed as indicated by the subsequent query to fetch all entity instances, which lists only two entity instances.

Figure 24. Running EJB V3 entity-bean client
Running EJB V3 entity-bean client

Conclusion

EJB V3.0 support is a new feature in WebSphere V7. The combination of Eclipse-WebSphere7-DB2 9.5 is ideally suited for developing EJB V3.0 entity beans.


Download

DescriptionNameSize
EJB 3.0 classesos-eclipse-ejb3-EJB3EntityBean.zip5KB

Resources

Learn

Get products and technologies

Discuss

  • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)
  • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.
  • Participate in developerWorks blogs and get involved in the developerWorks community.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Open source
ArticleID=480192
ArticleTitle=EJB V3.0 database persistence with Eclipse
publish-date=04062010