Building an EJB 3.0 Persistence Model with Oracle JDeveloper

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

EJB (Enterprise JavaBeans) 3.0 entity beans is a commonly used database persistence technology. EJB 3.0 has simplified the development of EJBs with an annotations-based APithat does not require remote/local interfaces, home/local home interfaces, or deployment descriptors. Developing entity EJBs requires an application server and a relational database, and optionally a Java EE IDE to simplify the process of development. The objective of the JSR-000220 Enterprise JavaBeans 3.0 specification ( http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html) is to improve the EJB architecture by reducing its complexity from the developer’s point of view. EJB 3.0 has introduced some new features, which include support for metadata annotations, default values for configuration, simplified access to environment variables, simplified session and entity beans, interceptors, enhanced support for checked
exceptions, and elimination of callback interfaces.
A number of books are available on EJB 3.0, but none cover EJB 3.0 on the Oracle Fusion Middleware (11g) platform. Most of the EJB 3.0 books are GlassFish server based, which has only 10percent of the application server market. Welcome to EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g, a book that will teach you how to leverage EJB 3.0 persistence on Oracle Fusion Middleware 11g. Oracle Fusion Middleware 11g includes many components such as the SOA/BPM Suite, WebCenter, and Oracle Identity Management. All of these components run on Oracle Weblogic Server 11g. The main development tool (IDE) for Oracle Fusion Middleware is Oracle JDeveloper. In respect of EJB 3.0, JDeveloper provides wizard support to reverse engineer database tables as EJB 3.0 entity beans. JDeveloper 11g also provides a wizard for creating session beans. The JPA persistence provider used in JDeveloper 11g is the EclipseLink persistence provider. JDeveloper comes with its own embedded/integrated Weblogic Server instance, which makes it very easy to develop and test within the one
environment. We shall be using the embedded WebLogic Server 11g in some of the chapters and the standalone WebLogic Server in others.
The objective of the book is to discuss the support of EJB 3.0 database persistence in Oracle Fusion Middleware 11g. While JDeveloper is the main Java IDE used in the book, one of the chapters leverages the Oracle Enterprise Pack for Eclipse. The book covers all aspects of EJB 3.0 database persistence including:

  • Creating EJB 3.0 entity beans from database tables
  • Creating session bean façades for entity beans
  • Entity beans with session beans
  • Creating EJB 3.0 entity relationships
  • Creating JSF and ADF Faces user interfaces (UIs) on top of EJB 3.0
    database persistence
  • Using EJB 3.0 database persistence in combination with Ajax and web services

also read:

What This Book Covers

In Chapter 1, What’s New in EJB 3.0, we discuss the new features in the EJB 3.0 specification, such as support for metadata annotations, default values for configuration, simplified session and entity beans, and enhanced support for checked exceptions.

In Chapter 2, Converting an EJB 2.0 Entity to an EJB, we convert an example EJB 2.0 entity bean to an EJB 3.0 entity bean. We also generate the session bean façade for the EJB 3.0 entity bean. XSLT transformation is used for converting the EJB 2.0 entity bean to an EJB 3.0 entity bean.

In Chapter 3, EclipseLink JPA Persistence Provider, we discuss the JPA framework and the EclipseLink persistence provider.

In Chapter 4, Building an EJB 3.0 Persistence Model with Oracle JDeveloper, we discuss EJB 3.0 database persistence with JDeveloper 11g, WebLogic Server 11g, and Oracle Database 10g. We create an EJB 3.0 entity bean from a database table, create a session bean façade, and finally create a JSP test client. Using the test client, we create, retrieve, and delete entity bean instances.
In Chapter 5, EJB 3.0 Persistence with Oracle Enterprise Pack for Eclipse, we discuss the same example we covered in Chapter 4, but with the Oracle Enterprise Pack for Eclipse, WebLogic Server, and the open source MySQL database, which has been acquired by Oracle.

In Chapter 6, EJB 3.0 with ADF Faces UI, we discuss using an ADF Faces client for EJB 3.0 database persistence. We create an entity bean using data input from an ADF Faces user interface (UI). Subsequently, we find an entity bean instance using data input from an ADF Faces UI.

In Chapter 7, Creating EJB 3.0 Entity Relationships, we discuss EJB 3.0 entity relationships using, as an example, three entity beans that have inter-relationships. We also discuss the significance of a fetch strategy.

In Chapter 8, EJB 3.0 Database Persistence with Ajax in the UI, we discuss EJB 3.0 database persistence in combination with Ajax in the user interface (UI). We demonstrate data validation and autocompletion with Ajax.

In Chapter 9, Using JSF with Entity Relationships, we discuss adding JSFs to EJB 3.0 database persistence to create and persist entity bean instances that have entity relationships between them.

In Chapter 10, Creating an EJB 3.0 Web Service, we create a JAX-WS Web Service from an EJB 3.0 entity bean, create a web service client, package and deploy the web service to WebLogic Server, and test the Web Service using the WebLogic console.

Building an EJB 3.0 Persistence Model with Oracle JDeveloper

Oracle Fusion Middleware is a family name for a set of Java EE products that are integrated for SOA and web application deployment. WebLogic Server (WLS) is the Java EE container and Oracle JDeveloper the Java EE and SOA development IDE. In this chapter, we will use JDeveloper to create an EJB 3.0 application, and then we will deploy and test our application leveraging the embedded WebLogic Server that comes with JDeveloper. This makes it very easy for us to develop, deploy, and test our application.
WebLogic server 10.x provides some value-added features to facilitate EJB 3 development. WebLogic server 10.x supports automatic deployment of a persistence unit based on the injected variable’s name. The @javax.persistence. PersistenceContext and @javax.persistence.PersistenceUnit annotation s are used to inject the persistence context in an EntityManager or EntityManagerFactory variable . A persistence context is a set of entities that are mapped to a database with a global JNDiname. If the name of the injected variable
is the same as the persistence unit, the unitName attribute of the @PersistenceContext or @PersistenceUnit is not required to be specified. The EJB container automatically deploys the persistence unit and sets its JNDiname to be the same as the persistence unit name in persistence.xml. For example, if the persistence unit name in the persistence.xml file is em, an EntityManager variable may be injected with the persistence context as follows:

	@PeristenceContext
	private EntityManager em;

We did not need to specify the unitName attribute in the @PersistenceContext because the variable name is the same as the persistence unit. Similarly, an EntityManagerFactory variable may be injected with the persistence context as follows, emf being also the persistence unit name:

	@PersistenceUnit
	private EntityManagerFactory emf;

Another value-added feature in WebLogic server 10.x is support for vendor-specific subinterfaces of the EntityManager interface . For example, the BEA Kodo persistence provider provides the KodoEntityManager subinterface , which may be injected with the persistence context as follows:

	@PersistenceContext
	private KodoEntityManager em;

Setting the environment

Before getting started, we need to install Oracle JDeveloper 11g, which may be downloaded from http://www.oracle.com/technology/products/jdev/index. html. Download the Studio Edition, which is the complete version of JDevloper
with all the features. Oracle JDeveloper 11g is distributed as a GUiself-extractor application. Click on the jdevstudio11110install application. The Oracle Installer gets started. Click on Next in the Oracle Installer. Choose a middleware home directory and click on Next.

Choose the Install Type as Complete, which includes the integrated WebLogic Server, and click on Next.

Confirm the default Product Installation directories and click on Next.  The WebLogic Server installation directory is the wlserver_10.3 folder within the middleware home directory. Choose a shortcut location and click on Next. The Installation Summary lists the products that are installed, which include the WebLogic Server and the WebLogic JDBC drivers. Click on Next to install Oracle JDeveloper 11g and the integrated WebLogic Server 10.3.


We also need to install the Oracle database 10g/11g or the lightweight Oracle XE , which may be downloaded from ttp://www.oracle.com/technology/software/products/database/index.html. When installing Oracle database, also install the sample schemas.

Creating a datasource in JDeveloper

Next, we create a JDBC datasource in JDeveloper. We shall use the datasource in the EJB 3.0 entity bean for database persistence. First, we need to create a database table in some sample schema, OE for example. Run the following SQL script in SQL *Plus:

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

A database table gets created in the OE sample schema.

Next, we need to create a JDBC connection in JDeveloper with Oracle database. Open the Database Navigator or select the Database Navigator tab if already open. Rightclick on the IDE Connections node and select New Connection.

In the Create Database Connection window, specify a Connection Name, select Connection Type as Oracle (JDBC), specify Username as OE, which is the schema in which the Catalog table is created, and specify the password for the OE schema. Select Driver as thin, Host Name as localhost, SID as ORCL, and JDBC Port as 1521. Click on the Test Connection button to test the connection. If the connection gets established, click on OK.

The OracleDBConnection gets added to the Database Navigator view. The CATALOG table that we created is listed in the Tables.

Creating an EJB 3.0 application

In this section, we create an EJB 3.0 application in JDeveloper. Select New Application.

Specify an Application Name, select the Java EE Web Application template, which consists of a Model project and a ViewController project, and click on Next.

Next, specify the name (EJB3ViewController) for the View and Controller project. In the Project Technologies tab, transfer the EJB project technology from the Available list to the Selected list using the > button. We have selected the EJB project technology, as we shall be creating an EJB 3.0 model. Click on Next.

Select the default Java settings for the View project and click on Next.

Configure the EJB Settings for the View project. Select EJB Version as Enterprise JavaBeans 3.0 and select Using Annotations. Click on Next. Next, create the Model project. Specify the Project Name (EJB3Model for example), and in the Project Technologies tab transfer the EJB project technology from the Available list to the Selected list using the > button. We have added the EJB project technology, as the
EJB 3.0 application client is created in the View project. Click on Next.


Select the default Java settings for the Model project and click on Next.

Similar to the View project, configure the EJB settings for the Model project. Select EJB Version as Enterprise JavaBeans 3.0, select Using Annotations and click on Finish. As we won’t be using a jndi.properties file or an ejb-jar.xml file , we don’t need to select the generate option for the jndi.properties file and the ejb-jar.xml file.

An EJB 3.0 application, which consists of a Model project and a ViewController project, get added in the Application tab.

Select the EJB3Model project in the Application navigator and select Tools | Project Properties. In the Project Properties window, select the Libraries and Classpath node. The EJB 3.0 library should be in the Classpath Entries.

Select the EJB Module node and select the OracleDBConnection in the Connection drop-down list. The datasource corresponding to the OracleDBConnection is jdbc/OracleDBConnectionDS.

Creating an EJB 3.0 entity bean

In this section we shall map an Oracle database table to an entity bean. Subsequently we shall discuss the components of the entity bean class.

Mapping an Oracle database table to an entity bean

In this section, we create an EJB 3.0 entity bean from the Oracle database table CATALOG that we created earlier. Select the EJB3Model project in the Application navigator and select File | New. In the New Gallery window, select Categories | Business Tier | EJB and Items | Entities from Tables, and click on OK.

In the Persistence Unit, window, select New to create a new persistence unit. In the New Persistence Unit window specify a persistence unit name (em). Specify JTA DataSource Name as jdbc/OracleDBConnectionDS, which is the datasource name corresponding to the OracleDBConnection connection. Select the default settings for Toplink: Server Platform as WebLogic 10. Click on OK.

The em Persistence Unit gets created. Click on OK in the Persistence Unit window.

Select Type of Connection as Online Database Connection and click on Next.

In the Database Connection Details window, select the OracleDBConnection and click on Next. We had configured a connection earlier, but the database connection can be created implicitly in the Database Connection Details, instead of explicitly.

In the Select Tables window, select Schema as OE, Name Filter as %, and check the Auto Query checkbox. Select the CATALOG table and click on Next.

Select the default settings in the General Options window. The default package name is model. In the Entity Class, select Place member-level annotations on as Fields, and select the Implement java.io.Serializable checkbox. Click on Next.

In the Specify Entity Details window, select Table Name as OE.CATALOG. As shown in the following screenshot, specify Entity Name as Catalog and Entity Class as model.Catalog. Click on Next.

The Summary page lists the EJB 3.0 JPA Entity that will be generated. In the Summary Page, click on Finish.

The CMP Entity bean class—model.Catalog—gets created. The persistence.xml deployment descriptor gets created in the META-INF directory.

The entity bean class

The entity bean class is just a POJO class annotated with the @Entity annotation . A @NamedQuery specifies a findAll query , which selects all the entity instances. An entity bean that has caching enabled is persisted to a database; the entity bean is serialized by caches. Therefore, the entity bean class implements the java. io.Serializable interface . Specify a serialVersionUID variable that is used by serialization runtime to associate a version number with the serializable class:

	private static final long serialVersionUID = 7422574264557894633L;

The database columns are mapped to entity bean properties, which are defined as private variables. The getter setter methods for the properties are also defined. The identifier property is specified with the @Id annotation. The @Column annotation specifies that the id column is not nullable:

	@Id
	@Column(nullable = false)
	private long id;

By default the id column of type INTEGER is mapped to a field of type Long. Modify the id field to type long, as usually id values are of primitive type. The entity bean class is listed next:

	package model;
	import java.io.Serializable;
	import javax.persistence.Column;
	import javax.persistence.Entity;
	import javax.persistence.Id;
	import javax.persistence.NamedQueries;
	import javax.persistence.NamedQuery;
	@Entity
	@NamedQueries({
		@NamedQuery(name = "Catalog.findAll", query = "select o from Catalog
		o")
	})
	public class Catalog implements Serializable {
		private String author;
		private String edition;
		private static final long serialVersionUID = 7422574264557894633L;
		@Id
		@Column(nullable = false)
		private long id;
		private String journal;
		private String publisher;
		private String title;
		public Catalog() {super();
		}
		public Catalog(String author, String edition, long id, String
			journal,
			String publisher, String title) {
			super();
			this.author = author;
			this.edition = edition;
			this.id = id;
			this.journal = journal;
			this.publisher = publisher;
			this.title = title;
		}
		public String getAuthor() {
			return author;
		}
		public void setAuthor(String author) {
			this.author = author;
		}
		public String getEdition() {
			return edition;
		}
		public void setEdition(String edition) {
			this.edition = edition;
		}
		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 getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
	}

The persistence.xml file is used to define the persistence unit/s, which include a JTA datasource that is used for database persistence. The persistence provider is specified as org.eclipse.persistence.jpa.PersistenceProvider. The jtadata-source is defined as java:/app/jdbc/jdbc/OracleDBConnectionDS. The eclipselink.target-server property is specified as WebLogic_10. The javax.persistence.jtaDataSource property is specified as java:/app/jdbc/jdbc/OracleDBConnectionDS, which is just the default mapping JDeveloper uses for the JTA Data Source. The java:/app/jdbc prefix gets added to the JTA Data Source specified when creating the persistence unit. The persistence.xml configuration file is listed next:

	<?xml version="1.0" encoding="windows-1252" ?>
		<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/

			persistence_1_0.xsd"
				version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
			<persistence-unit name="em">
				<provider>
					org.eclipse.persistence.jpa.PersistenceProvider
				</provider>
				<jta-data-source>
					java:/app/jdbc/jdbc/OracleDBConnectionDS
				</jta-data-source>
				<class>
					model.Catalog
				</class>
				<properties>
					<property name="eclipselink.target-server" value="WebLogic_10"
					/>
					<property name="javax.persistence.jtaDataSource"
					value="java:/app/jdbc/jdbc/OracleDBConnectionDS" />
				</properties>
			</persistence-unit>
		</persistence>

Creating EJB 3.0 a session bean

One of the best practices in, developing an entity bean is to wrap it in a session bean for a client. The entity bean is not directly accessed by a client. To create a session bean select the EJB3Model project and select File | New. In the New Gallery window, select Categories | Business Tier | EJB and Items | Session EJB. Click on OK.

Specify the EJB Name as CatalogTestSessionEJB. Select Session Type as Stateless and Transaction Type as Container. We have selected the stateless session bean because stateless session beans are less resource-intensive due to the lack of the overhead to keep the state of a unique client-bean session. Select the default mapped name (EJB3-SessionEJB). The Generate Session Façade Methods checkbox is selected by default. The Entity Implementation is JPA Entities by default. The persistence unit is em. Click on Next.

Select the default JPA Entity Methods to create and click on Next.

Specify the Bean Class (model.CatalogTestSessionEJBBean) and click on Next.

Select the EJB business interface to implement. Select the Implement a Remote Interface checkbox, specify the Remote interface (model.CatalogTestSessionEJB). Click on Next. The remote interface may be used in a distributed environment, but if using the client and the EJB 3.0 model in the same JVM, the local client view may be used.

The Summary page lists the session bean and the corresponding bean and interface classes that will be generated. In the Summary window, click on Finish.

The session bean class

A session bean class CatalogTestSessionEJBBean gets added to the entity bean model project. The remote business interface for the session bean, CatalogTestSessionEJB, also gets created.

The CatalogTestSessionEJBBean cl ass is annotated with the annotation @Stateless. The mappedName attribute specifies the global JNDifor the session bean. We shall use the mapped name in the test client to lookup the session bean and invoke method/s on it. The @Remote annotation indicates that the session bean is a remote interface.

	@Stateless(name = "CatalogTestSessionEJB", mappedName = "EJB3-
	SessionEJB")
	@Remote
	public class CatalogTestSessionEJBBean implements
	CatalogTestSessionEJB { }

In the session bean an EntityManager is injected using the @PersistenceContext annotation . The unitName is specified, but not required, as the EntityManager variable name is the same as the persistence unit name.

	@PersistenceContext(unitName = "em")
	private EntityManager em;

Add a method test() to the session bean and the remote interface. In the test() method, create a Catalog entity instance with the new operator:

	Catalog catalog =new Catalog("Kimberly Floss", "Nov-Dec 2004", new
	Integer(1),"Oracle Magazine", "Oracle Publishing","Database Resource
	Manager");

Invoke the persistEntity(Object) method to persist the entity bean instance:

	persistEntity(catalog);

The persistEntity method invokes the persist method of the EntityManager to persist the entity bean:

	em.persist(entity);

Similarly, persist two more entity bean instances. Next, create an instance of the Query object using the createQuery method to run a Java Persistence Query Language statement. Bind an author name to the named parameter :name using the setParameter method, and run the Java persistence query statement using the getResultList method , which returns a List:

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

Iterate over the List, which is actually just one catalog entry, to output field values for the journal, publisher, edition, title, and author fields:

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

Similarly, run a query to list all titles. Remove an entity instance using the remove method of the EntityManager. Subsequently, run a query to list all the remaining entity instances.

	em.remove(catalog2);

The test method returns a String, which consists of a catalog entry, a list of all the titles, and all the entity instances after removing an entity instance. The session bean class is listed next:

	package model;
	import java.util.Iterator;
	import java.util.List;
	import javax.ejb.Remote;
	import javax.ejb.Stateless;
	import javax.persistence.EntityManager;
	import javax.persistence.PersistenceContext;
	import javax.persistence.Query;
	@Stateless(name = "CatalogTestSessionEJB",
		mappedName = "EJB3-SessionEJB")
	@Remote
	public class CatalogTestSessionEJBBean implements
	CatalogTestSessionEJB {
		@PersistenceContext(unitName = "em")
		private EntityManager em;
		public CatalogTestSessionEJBBean() {
		}
		public String test() {
			Catalog catalog =
				new Catalog("Kimberly Floss", "Nov-Dec 2004", new Integer(1),
				"Oracle Magazine", "Oracle Publishing",
				"Database Resource Manager");
			persistEntity(catalog);
			Catalog catalog2 =
				new Catalog("Jonas Jacobi", "Nov-Dec 2004", new Integer(2),
				"Oracle Magazine", "Oracle Publishing",
				"From ADF UIX to JSF");
			persistEntity(catalog2);
			Catalog catalog3 =
				new Catalog("Steve Muench", "March-April 2005", new Integer(3),
				"Oracle Magazine", "Oracle Publishing",
				"Starting with Oracle ADF");
			persistEntity(catalog3);
			String retValue = "<b>A catalog entry: </b>";
			List catalogEntry =
				em.createQuery("SELECT c from Catalog c where c.author=:name").
				setParameter("name", "Jonas Jacobi").getResultList();
				for (Iterator iter = catalogEntry.iterator(); iter.hasNext(); ) {
					Catalog element = (Catalog)iter.next();
					retValue = retValue + "<br/>" + element.getJournal() + "<br/>" +
						element.getPublisher() + "<br/>" +
						element.getEdition() + "<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/>";
				}
				<b>return</b> retValue;
			}
			public Object mergeEntity(Object entity) {
				return em.merge(entity);
			}
			public Object persistEntity(Object entity) {
				em.persist(entity);
				return entity;
			}
			/** <code>select o from Catalog o</code> */
			public List<Catalog> queryCatalogFindAll() {
				return em.createNamedQuery("Catalog.findAll").getResultList();
			}
			/** <code>select o from Catalog o</code> */
			public List<Catalog> queryCatalogFindAllByRange(int firstResult,
				int maxResults) {
				Query query = em.createNamedQuery("Catalog.findAll");
				if (firstResult > 0) {
					query = query.setFirstResult(firstResult);
				}
				if (maxResults > 0) {
					query = query.setMaxResults(maxResults);
				}
				return query.getResultList();
			}
			public void removeCatalog(Catalog catalog) {
				catalog = em.find(Catalog.class, catalog.getId());
				em.remove(catalog);
			}
		}

The remote business interface is listed next:

	package model;
	import java.util.List;
	import javax.ejb.Remote;
	@Remote
	public interface CatalogTestSessionEJB {
		List<Catalog> queryCatalogFindAll();
		String test();
		List<Catalog> queryCatalogFindAllByRange(int firstResult,
			int maxResults);
		void removeCatalog(Catalog catalog);
	}

Creating and testing a test client

In this section, we create a JSP client to test the entity bean using a wrapper session bean.

Creating a client

First, we need to create a JSP. Select the EJB3ViewController project and select File>New. In the New Gallery window, select Categories | Web Tier | JSP and Items | JSP. Click on OK.

In the Create JSP window, specify a FileName (EJB3Client) and click on OK.

As we shall be invoking the entity bean, which is in the model project, from the JSP, which is in the ViewController project, we need to add a dependency in the ViewController project on the Model project. Select Tools | Project Properties and select Dependencies. Click on the Edit Dependencies button.

In the Edit Dependencies window, select EJB3Model | Build Output and click on OK, as shown:

The EJB3Model project gets added to the Dependencies. Click on OK, as shown next:

In the JSP client, we look up the session bean and invoke the test() method on it, which returns a String. First, we create an InitialContext:

	InitialContext context = new InitialContext();

Two methods are available to look up a session bean using the remote business interface.

  • Look up the session bean remote interface using the mapped name. The global JNDiname for a session bean remote business interface is derived from the remote business interface name. The format of the global JNDI name is mappedName#qualified_name_of_businessInterface.
  • Specify the business interface JNDiname in the weblogic-ejb-jar.xml deployment descriptor. The global JNDiname is specified as follows:
    	<weblogic-enterprise-bean>
    		<ejb-name>CatalogTestSessionEJBBean</ejb-name>
    		<stateless-session-descriptor>
    			<business-interface-jndi-name-map>
    				<business-remote>CatalogTestSessionEJB
    				</business-remote>
    				<jndi-name>EJB3-SessionEJB</jndi-name>
    			</business-interface-jndi-name-map>
    		</stateless-session-descriptor>
    	</weblogic-enterprise-bean>
    

We shall use the first method. Create a remote business interface instance using lookup with the mapped name:

	CatalogTestSessionEJB beanRemote = (CatalogTestSessionEJB) context.
	lookup("EJB3-SessionEJB#model.CatalogTestSessionEJB");

Invoke the test() method of the session bean:

	String catalog=beanRemote.test();

Output the string returned by the test method:

	<%=catalog %>

The EJB3Client is listed next:

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
		"http://www.w3.org/TR/html4/loose.dtd">
		<%@ page import="model.*, javax.naming.*" %>
		<%@ page
			contentType="text/html;charset=windows-1252"%>
		<html>
			<head>
				<meta http-equiv="Content-Type" content="text/html;
				charset=windows-1252" />
				<title>EJB3Client</title>
			</head>
			<body><% InitialContext context = new InitialContext();
				CatalogTestSessionEJB beanRemote = (CatalogTestSessionEJB)
				context.lookup("EJB3-SessionEJB#model.CatalogTestSessionEJB");
				String catalog=beanRemote.test(); %><%=catalog %></body>
		</html>

Testing the client

To run the test client, right-click on, EJB3Client.jsp and select Run.  The output from the test client lists a catalog entry, all the titles, and all the entity instances after removing a catalog entry.

Summary

In this section, we created an EJB 3.0 entity bean in JDeveloper 11g from an Oracle database table. The Catalog entity bean is automatically created a database table CATALOG; the database table columns are mapped to entity bean properties. We created a wrapper session bean for the entity bean, including a remote business interface. We added a test method to the session bean for creating and persisting entity instances, querying entity instances, and removing an entity instance. We created a JSP test client to test the entity bean. We look up the session bean remote interface using the mapped name for the session bean and invoke the test method on the remote interface instance. In the next chapter, we shall discuss EJB 3.0 database persistence with Oracle Enterprise Pack for Eclipse and WebLogic server.

also read:

Comments

comments

Speak Your Mind

*