Configuring and Deploying the EJB 3.0 Entity in WebLogic Server

Exclusive offer: get 80% off this eBook here
EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g — Save 80%

A complete guide to building EJB 3.0 database persistent applications with Oracle Fusion Middleware 11g tools with this book and eBook

₨1,016.00    ₨203.20
by Deepak Vohra | August 2010 | Enterprise Articles Oracle

In the previous article Developing an EJB 3.0 entity in WebLogic Server, we developed an EJB 3.0 entity using the Eclipse-WebLogic Server-MySQL combination.

In this article by Deepak Vohra, author of EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g, you will learn the following:

  • Creating a persistence configuration file
  • Creating a session bean
  • Creating a test client
  • Deploying the EJB 3.0 entity in WebLogic Server
  • Testing the EJB 3.0 entity client

(For more resources on Oracle, see here.)

Creating a Persistence Configuration file

An EJB 3.0 entity bean is required to have a persistence.xml configuration file, which defines the database persistence properties. A persistence.xml file gets added to the META-INF folder when a JPA project is defined. Copy the following listing to the persistence.xml file in Eclipse:

<?xml version="1.0" encoding="UTF-8" ?>
<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"
xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="em">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/MySQLDS</jta-data-source>
<class>ejb3.Catalog</class>
<properties>
<property name="eclipselink.target-server" value="WebLogic_10"
/>
<property name="javax.persistence.jtaDataSource" value="jdbc/
MySQLDS" />
<property name="eclipselink.ddl-generation"
value="create-tables" />
<property name="eclipselink.target-database" value="MySQL" />
</properties>
</persistence-unit>
</persistence>

The persistence-unit is required to be named and may be given any name. We had configured a JDBC data source with JNDI jdbc/MySQLDS in WebLogic Server. Specify the JNDI name in the jta-data-source element. The properties element specifies vendor-specific properties. The eclipselink.ddl-generation property is set to create-tables, which implies that the required database tables will be created unless they are already created . The persistence.xml configuration file is shown in the Eclipse project in the following illustration:

(Move the mouse over the image to enlarge.)

Creating a session bean

For better performance, one of the best practices in developing EJBs is to access entity beans from session beans. Wrapping an entity bean with a session bean reduces the number of remote method calls as a session bean may invoke an entity bean locally. If a client accesses an entity bean directly, each method invocation is a remote method call and incurs an overhead of additional network resources. We shall use a stateless session bean, which consumes less resources than a stateful session bean, to invoke entity bean methods. In this section, we create a session bean in Eclipse. A stateless session bean class is just a Java class annotated with the @Stateless annotation. Therefore, we create Java classes for the session bean and session bean remote interface in Eclipse. To create a Java class, select File | New. In the New window, select Java | Class and click on Next>

In the New Java Class window, select the Source folder as EJB3JPA/src, EJB3JPA being the project name. Specify Class Name as CatalogTestBean and click on Finish.

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

Similarly, create a CatalogTestBeanRemote interface by selecting Java | Interface in the New window. The session bean class and the remote interface get added to the EJB3JPA project.

The session bean class

The stateless session bean class, CatalogTestBean implements the CatalogTestRemote interface. We shall use the EntityManager API to create, find, query, and remove entity instances. Inject an EntityManager using the @PersistenceContext annotation. Specify unitName as the same as the persistence-unit name in the persistence.xml configuration file:

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

Next, create a test() method, which we shall invoke from a test client. In the test() method we shall create and persist entity instances, query an entity instance, and delete an entity instance, all using an EntityManager object, which we had 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), "Oracle Magazine",
"Oracle Publishing", "September-October 2009",
"Put Your Arrays in a Bind","Mark Williams");

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 query string may be specified as a EJB-QL query. Unlike HQL, the SELECT clause is not optional in EJB-QL. Execute the query and return the query result as a List using the getResultList() method. As an example, select the catalog entry corresponding to author David Baum. The FROM clause of a query is directed towards the mapped entity bean class, not the underlying database.

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

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/>";
}

The variable retValue is a String that is returned by the test() method. Similarly, 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 gets deleted from the Catalog table. Subsequently, create and run a query to list all the entity instances mapped to the database. The session bean class, CatalogTestBean, is listed next:

package ejb3;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Session Bean implementation class CatalogTestBean
*/
@Stateless(mappedName = "EJB3-SessionEJB")
public class CatalogTestBean implements CatalogTestBeanRemote {
@PersistenceContext(unitName = "em")
EntityManager em;

/**
* Default constructor.
*/
public CatalogTestBean() {
// TODO Auto-generated constructor stub
}

public String test() {
Catalog catalog = new Catalog(new Integer(1), "Oracle Magazine",
"Oracle Publishing", "September-October 2009",
"Put Your Arrays in a Bind","Mark Williams");
em.persist(catalog);
Catalog catalog2 = new Catalog(new Integer(2), "Oracle Magazine",
"Oracle Publishing", "September-October 2009",
"Oracle Fusion Middleware 11g: The Foundation for Innovation",
"David Baum");
em.persist(catalog2);
Catalog catalog3 = new Catalog(new Integer(3), "Oracle Magazine",
"Oracle Publishing", "September-October 2009",
"Integrating Information","David Baum");
em.persist(catalog3);
String retValue = "<b>Catalog Entries: </b>";
List catalogEntry = em.createQuery("SELECT c from Catalog c
where c.author=:name").setParameter("name",
"David Baum").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;
}
}

We also need to add a remote or a local interface for the session bean:

package ejb3;
import javax.ejb.Remote;
@Remote
public interface CatalogTestBeanRemote {
public String test();
}

The session bean class and the remote interface are shown next:

We shall be packaging the entity bean and the session bean in a EJB JAR file, and packaging the JAR file with a WAR file for the EJB 3.0 client into an EAR file as shown next:

EAR File
|
|
|-WAR File
|
|-EJB 3.0 Client
|-JAR File
|
|-EJB 3.0 Entity Bean
EJB 3.0 Session Bean

Next, we create an application.xml for the EAR file. Create a META-INF folder for the application.xml. Right-click on the EJB3JPA project in Project Explorer and select New>Folder. In the New Folder window, select the EJB3JPA folder and specify the new Folder name as META-INF. Click on Finish. Right-click on the META-INF folder and select New | Other. In the New window, select XML | XML and click on Next. In the New XML File window, select the META-INF folder and specify File name as application.xml. Click on Next. Click on Finish.

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

An application.xml file gets created. Copy the following listing to application.xml:

<?xml version = '1.0' encoding = 'windows-1252'?>
<application>
<display-name></display-name>
<module>
<ejb>ejb3.jar</ejb>
</module>
<module>
<web>
<web-uri>weblogic.war</web-uri>
<context-root>weblogic</context-root>
</web>
</module>
</application>

The application.xml in the Project Explorer is shown next:

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g A complete guide to building EJB 3.0 database persistent applications with Oracle Fusion Middleware 11g tools with this book and eBook
Published: August 2010
eBook Price: ₨1,016.00
Book Price: ₨1,694.00
See more
Select your format and quantity:

(For more resources on Oracle, see here.)

Creating a test client

We have created an entity bean that contains the business logic. We have created a session bean that is a wrapper for the entity bean. Next, we shall create a test client JSP in which we shall invoke the test() method of the session bean. For the web application component, we need to create a web module folder, a WEB-INF folder in the web module folder and a web.xml in the WEB-INF folder. To create a JSP in the webModule folder, right-click on the webModule folder and select New | Other.

In the New window, select Web | JSP and click on Next.

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

In the New Java Server Page window, select the webModule folder and specify the JSP File name as catalog.jsp. Click on Finish, as shown next:

The catalog.jsp JSP gets added to the webModule folder. The catalog.jsp is shown below, including the JSP code, which we shall discuss next:

We shall create an instance of CatalogTestRemote using JNDI lookup for which we need to create an IntialContext object. We need to set the InitialContext environment using the environment properties:

InitialContext context = new InitialContext();

Obtain a CatalogTestBeanRemote instance using remote JNDI lookup on the session bean remote object. The JNDI name for WebLogic server is of the format mapped_name#remote_interface_class_name.

CatalogTestBeanRemote beanRemote = (CatalogTestBeanRemote) context.
lookup("EJB3-SessionEJB#ejb3.CatalogTestBeanRemote");

Invoke the test() method of the session bean and output the String returned, as shown next:

String catalog=beanRemote.test();

The test client JSP is listed next:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="ejb3.*, javax.naming.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><% InitialContext context = new InitialContext();
CatalogTestBeanRemote beanRemote = (CatalogTestBeanRemote)
context.lookup("EJB3-SessionEJB#ejb3.
CatalogTestBeanRemote");
String catalog=beanRemote.test(); %><%=catalog %>
</body>
</html>

Deploying the entity in WebLogic Server

We have created all the classes and configuration files we need to create an EJB 3.0 entity bean. Next, we shall compile the classes to create a EJB JAR file. We shall create a WAR file from the EJB 3.0 client JSP and package the WAR file with the JAR file into an EAR file. We shall use a build.xml script to compile the EJB classes, create an EAR file, and deploy the EAR file to WebLogic Server. Create a build.xml script in the JPA project with File | New | Other and XML | XML in the New window. The build.xml script is shown next:

In the build script, specify properties for the various directory paths used in the script, such as the WebLogic server directory, the build directory, and the WebLogic Server deploy directory. Specify the classpath of the various JAR files required for compiling the EJB classes. Specify targets discussed in the following table:

Target

Description

prepare

Creates the build directory.

compile

Compiles the EJB classes.

jar

Creates an EJB JAR file.

war

Creates a WAR file.

assemble-app

Creates an EAR file.

deploy

Deploys the EAR file to WebLogic Server. The WebLogic Server deploy directory development mode is ${weblogic.home}/user_projects/domains/ base_domain/autodeploy

clean

Deletes the build directory and the EJB JAR, WAR and EAR files.

 

The build.xml script is listed next:

<?xml version="1.0" encoding="UTF-8"?>
<!--
WebLogic build file
-->
<project name="EJB3EntityBean" default="deploy" basedir=".">
<property environment="env" />
<property name="src.dir" value="${basedir}/src" />
<property name="web.module" value="${basedir}/webModule" />
<property name="weblogic.home" value="C:/Oracle/Middleware/wls" />
<property name="weblogic.server"
value="${weblogic.home}/wlserver_10.3/server" />
<property name="build.dir" value="${basedir}/build" />
<property name="deploy.dir"
value="${weblogic.home}/user_projects/domains/base_domain/
autodeploy" />
<path id="classpath">
<fileset dir="${weblogic.home}/modules">
<include name="*.jar" />
</fileset>
<fileset dir="${weblogic.server}/lib">
<include name="*.jar" />
</fileset>
<pathelement location="${build.dir}" />
</path>
<property name="build.classpath" refid="classpath" />
<target name="prepare">
<mkdir dir="${build.dir}" />
</target>
<target name="compile" depends="prepare">
<javac srcdir="${src.dir}" destdir="${build.dir}" debug="on"
includes="**/*.java">
<classpath refid="classpath" />
</javac>
</target>
<target name="jar" depends="compile">
<jar destfile="${build.dir}/ejb3.jar">
<fileset dir="${build.dir}">
<include name="**/*.class" />
</fileset>
<fileset dir="${src.dir}/">
<include name="META-INF/persistence.xml" />
</fileset>
</jar>
</target>
<target name="war" depends="jar">
<war warfile="${build.dir}/weblogic.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}/ejb3.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}/ejb3.ear" todir="${deploy.dir}" />
</target>
<target name="clean">
<delete file="${build.dir}/ejb3.ear" />
<delete file="${build.dir}/ejb3.jar" />
<delete file="${build.dir}/weblogic.war" />
</target>
</project>

Next, run the build script. Right-click on the build.xml script in the Package Explorer and select Run As | Ant Build (the second Ant Build), as shown in the following screenshot:

In the Edit Configuration window, select the target(s) to run. The default build target in the build script is deploy with each target having a dependence on the preceding target. The prepare, compile, jar, war, and assemble-app targets run when the deploy target is run. Select the deploy target and click on Apply. Click on Run to run the deploy target and thus deploy the EAR file to the WebLogic Server autodeploy directory.

All the targets get run and the EAR file gets deployed to the WebLogic Server, as shown in the build script output:

Start the WebLogic Server, if not already started, and log in to the Administration Console. Navigate to the Deployments node. The EAR file is shown as deployed in the Deployments table:

Testing the EJB 3.0 entity client

Next, run the client JSP in a browser with the URL http://localhost:7001/weblogic/catalog.jsp. The test() method of the session bean gets invoked. Three entity bean instances get created and persisted to the MySQL database. As shown in the server output, the entity bean property values for the entity instance corresponding to author David Baum get listed. The titles of all the three entity instances get listed. Subsequently, an entity instance gets removed, as indicated by the subsequent query to fetch all entity instances, which lists only two entity instances.

EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g

Summary

In this article, we created a wrapper session bean in Oracle Enterprise Pack for Eclipse, packaged the application into an EAR file, and deployed the application to WebLogic Server using a build script. Subsequently, we ran the application in WebLogic server with a MySQL database as the EJB 3.0 persistence database.


Further resources on this subject:


EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g A complete guide to building EJB 3.0 database persistent applications with Oracle Fusion Middleware 11g tools with this book and eBook
Published: August 2010
eBook Price: ₨1,016.00
Book Price: ₨1,694.00
See more
Select your format and quantity:

About the Author :


Deepak Vohra

Deepak Vohra is a consultant and a principal member of the NuBean.com software company. Deepak is a Sun Certified Java Programmer and Web Component Developer, and has worked in the fields of XML and Java programming and J2EE for over five years. Deepak is the co-author of the Apress book Pro XML Development with Java Technology and was the technical reviewer for the O'Reilly book WebLogic: The Definitive Guide. Deepak was also the technical reviewer for the Course Technology PTR book Ruby Programming for the Absolute Beginner, and the technical editor for the Manning Publications book Prototype and Scriptaculous in Action. Deepak is also the author of the Packt Publishing books JDBC 4.0 and Oracle JDeveloper for J2EE Development; Processing XML documents with Oracle JDeveloper 11g; EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g; and Java 7 JAX-WS Web Services.

Books From Packt


The Oracle Universal Content Management Handbook
The Oracle Universal Content Management Handbook

Oracle SOA Suite 11g R1 Developer's Guide
Oracle SOA Suite 11g R1 Developer's Guide

BPEL PM and OSB operational management with Oracle Enterprise Manager 10g Grid Control
BPEL PM and OSB operational management with Oracle Enterprise Manager 10g Grid Control

The Business Analyst's Guide to Oracle Hyperion Interactive Reporting 11
The Business Analyst's Guide to Oracle Hyperion Interactive Reporting 11

Oracle Coherence 3.5
Oracle Coherence 3.5

EJB 3 Developer Guide
EJB 3 Developer Guide

Oracle Siebel CRM 8 Installation and Management
Oracle Siebel CRM 8 Installation and Management

Oracle Database 11g – Underground Advice for Database Administrators
Oracle Database 11g – Underground Advice for Database Administrators


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software