Skip Headers
Oracle® Fusion Middleware User's Guide for Oracle JDeveloper
11g Release 2 (11.1.2.3.0)

Part Number E17455-04
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

12 Developing with EJB and JPA Components

This chapter describes how to use JDeveloper tools to build the business tier of a J2EE enterprise application using Enterprise JavaBeans (EJB) 3.0 and Java Persistence API (JPA) components.

This chapter includes the following sections:

12.1 About Developing with EJB and JPA Components

JDeveloper includes step-by-step wizards for creating EJB projects, entities, persistence units, session beans, and message-driven beans. You can build entities from online or offline database definitions and from application server data source connections. There is also seamless integration with JPA and TopLink technology to provide a complete persistence package.

12.2 Support For EJB Versions and Features

JDeveloper supports EJB 3.0, as well as versions 1.0 through 2.1. The current JDeveloper documentation, including this chapter of the User Guide and the embedded online help, focus on EJB 3.0 development tasks.

Previous versions of the JDeveloper documentation tell how to work with EJB 2.1 and earlier. For those versions of the documentation, see http://www.oracle.com/webapps/online-help/jdeveloper/10.1.3 and search for and navigate to the topic "Developing Enterprise JavaBean Components." Be aware that EJB application development interfaces may change from version to version, and some historical help content will be outdated for the current version.

For the complete EJB Java Community Process specifications and documentation for all versions, see the Oracle Technology Network at http://www.oracle.com/technetwork/java/docs-135218.html.

Note:

If you are using EJB 3.0, you may be using annotations instead of some deployment files. Include deployment descriptors to override annotations or specify options not supported by annotations.

Supported EJB 3.0 Features

The key differences between EJB 3.0 and previous versions are:

Session Beans

Message-Driven Beans (MDBs)

Entities - Java Persistence API (JPA)

12.3 Building EJB 3.0 Applications and Development Process

JDeveloper includes a complete set of features to set up the EJB business layer of an enterprise application.

You can start by using the step-by-step wizard to create the framework for your EJB web application, setting up the model layer of your enterprise application. You can then use wizards to create entities that correspond to database tables. You can then use a wizard to create session beans and facades and to build a persistence unit. Oracle ADF provides components to enable data controls. When you are ready, you can use the JDeveloper integrated server capabilities to test it.

12.3.1 EJB 3.0 Application Development Process

JDeveloper includes tools for developing EJB applications, as described in the following sections.

12.3.1.1 Creating Entities

Use the entity wizards to create entities or to create entities from tables using online, offline, or application server data source connections. Use the Entity Beans from Tables Wizard to reverse-engineer entities from database tables. In the entity wizards you can select or add a a persistence unit and a database connection, or you can select a database to emulate. You can also select database tables for your entity. For more information, see Section 12.6.2, "How to Create JPA Entities".

You can create entities from existing tables, or manually in the Java Source Editor. If you create entities from existing tables, the mapping is done automatically. If you create entities manually, you have more control over the mapping, but you must code it by hand. You can create entities using wizards or by using an EJB diagram.

12.3.1.2 Creating Session Beans and Facades

You can use session beans to implement the session facade design pattern. A session facade aggregates and presents data, provides a place for business logic, and has a transactional context via the container. For more information, see Section 12.7, "Implementing Business Processes in Session Beans" and Section 12.7.1, "Using Session Facades".

When you create a session bean with the wizard, you have the option of generating session facade methods for every entity in the same project. You can choose which core transactional methods to generate, get() and set() accessors, and finder methods on the entities. If you create new entities or new methods on entities, you can update your existing session facade by right-clicking it in the Navigator and choosing Edit Session Facade.

12.3.1.3 Deploying EJBs

JDeveloper provides Oracle WebLogic Server as a container for deployed EJBs. A JDeveloper server-specific deployment profile is generated by default. You can also create a WebLogic-specific deployment profile. For more information, see Section 12.9, "Deploying EJB Modules and JPA Persistence Units".

12.3.1.4 Testing EJBs Remotely

JDeveloper can also create a sample client for use with a remote server. You generate the sample client in the same manner as a local client, providing the remote connection details. For more information, see Section 12.10.2, "How to Test EJB/JPA Components Using a Remote Server".

12.3.1.5 Registering Business Services with Oracle ADF Data Controls

ADF provides components for enabling data controls for your entities. Your Java EE application integrates selective components as you manually add a data control for your entities. For more information, see "Using ADF Model Data Binding in a Java EE Web Application" in Oracle Fusion Middleware Java EE Developer's Guide for Oracle Application Development Framework.

12.4 How to Work with an EJB Business Services Layer

Create a model business services layer for a web-based EJB 3.0 application.

To create a web-based application:

To create JPA entities:

  1. In the Application Navigator, select Model.

  2. Choose File, then New, then Business Tier, then EJB, then Entity or Entity from Tables.

  3. When you get to the Persistence Unit page, click Next to automatically create a default persistence unit, persistence.xml, or click New to create a new persistence grouping within the existing META-INF/persistence.xml file.

  4. Follow the remaining steps in the wizard to create JPA entities.

To implement a session facade:

  1. In the Application Navigator select Model.

  2. Choose File, then New, then Business Tier, then EJB, then Session Bean.

  3. Follow the steps in the wizard.

    When you get to the EJB Name and Options page, be sure to check Generate Session Facade Methods.This automatically adds the session facade methods to your session bean. Note that you can create and edit session facade methods for all entities in your project by right-clicking your session bean and choosing Edit Session Facade. JDeveloper automatically recognizes new entities in your project and new methods on the entities.

To register the business services model project with the data control:

To run and test your application:

To deploy your application:

The integrated server runs within JDeveloper. You can run and test EJBs using this server and then deploy your EJBs with no changes to them. You do not need to create a deployment profile to use this server, nor do you have to initialize it. Create the deployment descriptor, ejb-jar.xml using the Deployment Descriptor wizard, and then package your EJB modules for deployment with your application.

12.5 Using Java EE Design Patterns in Oracle JDeveloper

The Java EE design patterns are a set of best practices for solving recurring design problems. Patterns are ready-made solutions that can be adapted to different problems, and leverage the experience of successful Java EE developers.

JDeveloper can help you implement the following Java EE design patterns in your EJB applications:

12.6 Building a Persistence Tier

The persistence tier is the part of your EJB application that contains all of the persistent data object that represent tables in a database. These business components are called JPA entities since the entity model introduced in EJB 3.0 is defined in the Java Persistence API.

12.6.1 About JPA Entities and the Java Persistence API

JPA entities adopt a lightweight persistence model designed to work seamlessly with Oracle TopLink and Hibernate.

The major enhancements with JPA entities are:

  • JPA Entities are POJOs

  • Metadata Annotations for O-R Mapping

  • Inheritance and Polymorphism Support

  • Simplified EntityManager API for CRUD Operations

  • Query Enhancements

12.6.1.1 JPA Entities are POJOs

JPA entities are now POJOs (Plain Old Java Objects) and there are no component interfaces required for them. JPA entities support inheritance and polymorphism as well.

Example 12-1 contains the source code for a simple JPA entity.

Example 12-1 Source code for a simple JPA entity

@Entity 
@Table(name = "EMP") 
public class Employee implements java.io.Serializable 
{
   private int empNo; 
   private String eName; 
   private double sal; 
   @Id 
   @Column(name="EMPNO", primaryKey=true) 
     public int getEmpNo() 
     {
       return empNo; 
     }
public void setEmpNo(int empNo)
{
  this.empNo = empNo; 
}
 public double getSal() 
{
   return sal; 
}
...
}

Note that the bean class is a concrete class, not an abstract one, as was the case with CMP 2.x entity beans.

12.6.1.2 Metadata Annotations for O-R Mapping

The O-R mapping annotations allow users to describe their entities with O-R mapping metadata. This metadata is then used to define the persistence and retrieval of entities. You no longer have to define the O-R (object Relational) mapping in a vendor-specific descriptor.

The example above uses the @Entity, @Table, and @Column annotations to specify at the class level that this is an entity, and to specify the underlying database table and column names for the entity. You can also use mapping annotations to define a relationship between entities, as shown in Example 12-2.

Example 12-2 Mapping Annotations

@ManyToOne(cascade=PERSIST) 
@JoinColumn(name="MANAGER_ID", referencedColumnName="EMP_ID") 
public Employee getManager() 
{
  return manager; 
}

12.6.1.3 Inheritance and Polymorphism Support

Inheritance is very useful in many scenarios. The two types of inheritance that are commonly used and supported by Oracle Application Server for JPA entities are:

  • Single table per class hierarchy

  • Joined sub class strategy

The inheritance can be expressed using annotations. Example 12-3 contains code that uses the joined sub class strategy.

Example 12-3 Joined Subclass Strategy

@Entity 
@Table(name="EJB_PROJECT") 
@Inheritance(strategy=JOINED, discriminatorValue="P") 
@DiscriminatorColumn(name="PROJ_TYPE") 
public class Project implements Serializable 
{
...
}
@Entity 
@Table(name="EJB_LPROJECT") 
@Inheritance(discriminatorValue="L") 
public class LargeProject extends Project
{
...
}
@Entity 
@Table(name="EJB_PROJECT") 
@Inheritance(discriminatorValue="S") 
public class SmallProject extends Project 
{
...
}

12.6.1.4 Simplified EntityManager API for CRUD Operations

The javax.persistence.EntityManager API is used for CRUD (Create, Read, Update, and Delete) operations on entity instances. You no longer have to write code for looking up instances and manipulating them. You can inject an instance of EntityManager in a session bean and use persist() or find() methods on an EntityManager instance to create or query entity bean objects, as show in Example 12-4.

Example 12-4 EntityManager in a Session Bean

@PersistenceContext
private EntityManager em; 
private Employee emp; 
    public Employee findEmployeeByEmpNo(int empNo) 
    { 
       return ((Employee) em.find("Employee",empNo)); 
     }
public void addEmployee(int empNo, String eName, double sal)
{ 
   if (emp == null) emp = new Employee(); 
   emp.setEmpNo(empNo); 
   ...
   em.persist(emp); 
}
}

12.6.1.5 Query Enhancements

Queries are defined in metadata. You may now specify your queries using annotations, or in a deployment descriptor. JPA entities support bulk updates and delete operations through JPQL (Java Persistence Query Language). For more information, see Section 12.6.7, "JDK 5 Annotations for EJB/JPA".

12.6.2 How to Create JPA Entities

JDeveloper offers you two easy wizards to create your JPA entities. You can create entities from online or offline databases, add a persistence unit, define inheritance strategies, and select from available database fields. The Entity from Tables wizard allows you to create entities from online or emulated offline databases, as well as from a application server data sources.

To create entities or entities from tables:

  1. Choose File menu, then New, then Business Tier, then EJB, then Entity or Entities from Tables.

  2. Follow the steps in the wizard.

To create EJBs in an existing module:

  1. In the Navigator, right-click an EJB module and choose New, then EJB, then Entity or Entities from Tables.

    Or, choose File menu, then New, then Business Tier, then EJB, then Entity or Entities from Tables.

  2. Follow the steps in the wizard.

To create EJBs in a new EJB module:

  1. Choose File menu, then New, then General, then Projects.

  2. Select the type of project you want to create and click OK.

  3. In the Navigator, right-click on the new project and choose New.

    Or, select the module and choose File menu, then New, then Business Tier, then EJB, then Entity or Entities from Tables.

12.6.3 About SDO For EJB/JPA

JDeveloper provides support for the SDO (Service Data Objects) data application development framework.

Use the SDO 2.0 framework and API to easily modify business data regardless of how it is physically accessed. SDO encapsulates the backend data source, offers a choice of static or dynamic programming styles, and supports both connected and disconnected access. SDO handles XML parser operations, and automatically integrates the data parsing logic with the application. For more information, "Integrating Service-Enabled Application Modules" in Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework.

The SDO architecture supported by JDeveloper offers the following:

  • Simplifies the J2EE data programming model

  • Abstracts data in a service oriented architecture (SOA)

  • Unifies data application development by creating a standard way of passing data between clients

  • Supports and integrates XML

  • Incorporates J2EE patterns and best practices

SDO is a unified framework for data application based on the concept of disconnected data graphs. A data graph is a collection of tree-structured or graph-structured data objects. To enable development of generic or framework code that works with Data Objects, it is important to be able to introspect on Data Object metadata, which exposes the data model for the Data Objects. As an alternative to Java reflection, SDO provides APIs to access metadata stored in XML schema definition (XSD) files that you create, based on the entity or data model information detailed in your EJB session beans.

12.6.4 Using an EJB/POJO-based ADF-BC Service for Deployment to the SOA Platform

The SDO feature in JDeveloper can be used as an EJB service or as an ADF-BC service. If you choose to use an ADF-BC service you need add the listener reference to your weblogic-application.xml file. For more information, see Section 12.6.5, "How to Create an SDO Service Interface for JPA Entities".

For more information and specifications on SDO, see the OSOA (Open Service Oriented Architecture) at http://www.oasis-opencsa.org/

12.6.5 How to Create an SDO Service Interface for JPA Entities

You can easily create a service interface API to access JPA entity data through either an EJB session bean or a plain old Java object (POJO). This service class exposes operations for creating, retrieving, updating, and deleting the JPA entities in your JDeveloper J2EE application.

To create a SDO service interface:

  1. Start with an EJB session bean, or an ordinary Java class (POJO), that exposes CRUD methods for one or more JPA entities.

    You can use the wizard to create your session beans. For more information, see Section 12.7.2, "How to Create a Session Bean".

  2. In the Structure window, right-click your EJB session Bean or POJO and choose Create Service Interface.

  3. Select the methods you want to make available in your service API.

    By default all of the methods in your session bean interface are selected. Click the checkbox to select or unselect a method.

  4. In this release, when you create a service interface, your original session bean file and the remote (or local) interface are modified. New methods are added that match the original ones, but they reference newly defined SDO data objects instead of JPA entities. These SDO data objects match the JPA entities and are defined in XSD files, which are also added to your project, and their names are appended with SDO, such as DeptSDO or EmployeeSDO. Select Backup File(s) to create a backup of your original session bean file.

  5. Click OK.

12.6.5.1 How to Configure an EJB/POJO-based ADF-BC Service for Deployment to the SOA Platform

To use an EJB/POJO SDO ADF-BC service from a fabric composite using SDO external bindings, you need to set up the Weblogic application deployment listener to invoke the ServiceRegistry logic. Set this up by adding the listener reference to your weblogic-application.xml file.

To add the listener reference:

Add the code in Example 12-5 to the weblogic-application.xml which by default is located in <workspace-directory>/src/META-INF.

Example 12-5 Code Added to weblogic-application.xml

<listener>
<listener-class> oracle.jbo.client.svc.ADFApplicationLifecycleListener
</listener-class>
</listener>

Once this listener is added, JDeveloper automatically registers the SDO service application name _JBOServiceRegistry_ into the fabric service registry in the composite.xml.

12.6.5.2 File Types Created to Support Your SDO Architecture

When you create your SDO service interface, the necessary files to support your service interface are automatically created. These files include the following:

  • SessionEJBBeanWS.wsdl - This file describes the capabilities of the service that provides an entry point into an SOA application or a reference point from an SOA application. The WSDL file provides a standard contract language and is central for understanding the capabilities of a service.

  • SessionEJBBeanWS.xsd - This is an XML schema file that defines your service interface methods in terms of SDO data types. All of the entities that were contained in your session bean interface will have a corresponding DataObject element in this schema file. At runtime, these DataObjects are registered with the SDO runtime by calling XSDHelper.INSTANCE.define() method. A static type-specific DataObject is defined for each SDO type.

12.6.6 How to Generate Database Tables from JPA Entities

When you deploy the JDeveloper integrated server, database tables are automatically created for every entity that does not have a corresponding existing mapped table. One database table will be generated per unmapped JPA entity.

Note:

Primary key referential integrity constraints will be generated, but other constraints may not be.

To generate database tables from JPA entities:

  1. Create your JPA entity using the modeling tools or the Create Entity wizards. For more information, see Section 12.6.2, "How to Create JPA Entities.".

  2. Modify the entities as necessary, adding fields and constraints.

  3. Name the tables:

  4. Deploy the persistence unit. For more information, see Section 12.9, "Deploying EJB Modules and JPA Persistence Units.".

12.6.7 JDK 5 Annotations for EJB/JPA

Annotations can simplify your development tasks by reducing the number of deployment descriptors needed for your application components. Annotations can also be used to generate artifacts such as interfaces.

An annotation is a metadata modifier that is added to a Java source file. Annotations are compiled into the classes by the Java compiler at compile time, and can be specified on classes, fields, methods, parameters, local variables, constructors, enumerations, and packages. Annotations can be used to specify attributes for generating code, for documenting code, or for providing services like enhanced business-level security or special business logic during runtime.

Every type of annotation available for your EJB/JPA classes can also, alternatively, be added to an XML deployment descriptor file. At runtime the XML will override any annotations added at the class level.

Annotations are marked with the @ symbol, such as this stateless session bean annotation:

@Stateless public class MySessionBean

For more information on annotations for EJB 3.0, see http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

Note:

Annotations are new to EJB 3.0, and not available for previous versions of EJB.

During design time, JDeveloper displays a list of available annotations through the Property Inspector. You can change any suitable Java class to an EJB or JPA component using the annotation feature. For more information, see Section 12.6.8, "How to Annotate Java Classes.".

12.6.7.1 EJB 3.0

Annotations are available to indicate the bean type. Adding your bean type annotation to a regular class turns it into an EJB.

The following types of annotations are available:

  • Is Stateless Session Bean. Choose TRUE or FALSE to annotate your class as a stateless session bean.

  • Is Stateful Session Bean. Choose TRUE or FALSE to annotate your class as a stateful session bean.

  • Is Message Driven Bean. Choose TRUE or FALSE to annotate your class as a message driven bean.

12.6.7.2 JPA 1.0

Annotations support a new Java Persistence API as an alternative to entity beans.

The following types of annotations are available:

  • Is JPA Entity. Choose TRUE or FALSE to annotate your class as a JPA entity.

  • Is JPA Mapped Superclass. Choose TRUE or FALSE to annotate your class as a JPA mapped superclass.

  • Is JPA Embeddable. Choose TRUE or FALSE to annotate your class as JPA embeddable.

Once you transform your regular Java class into an EJB/JPA component, or if you used one of the EJB/JPA wizards to create the component, the Property Inspector displays a different set of contextual options, which you can use to add or edit annotations for the various members within the component class.

12.6.8 How to Annotate Java Classes

During design time, JDeveloper provides you with the list of available annotations to insert into your classes. The options change depending on what type of class you are working on, and what member you have selected.

You can annotate any regular Java class to turn it into an EJB/JPA component. Once the class is defined with annotations as an EJB/JPA, you can easily customize the component with a variety of member-level annotations available to choose from in the JDeveloper Property Inspector.

Note:

Annotations are only available for EJB 3.0, and not available for previous versions of EJB.

To annotate your Java class as an EJB/JPA component:

  1. In the Application Navigator, select the class you want to transform.

  2. In the Structure window, double-click the class name.

    If your class is already open in the Java source editor, put your curser in the class definition line.

  3. Open the Property Inspector, select the EJB/JPA tab and choose the type of component you want to create. Select True.

After your Java class is annotated as an EJB/JPA component, the EJB/JPA tab disappears from the Property Inspector and a new tab appears, specific to the component type you chose. To change the component back to a regular Java class, remove the annotation from the code to reset the EJB/JPA component types displayed in the Property Inspector.

Note:

EJB or JPA components created through the wizards already contain the class type annotations. For more information, see Section 12.3, "Building EJB 3.0 Applications and Development Process.".

Once your Java class is transformed into an EJB/JPA component using a class-level annotation, use the Property Inspector to add or edit annotations to member fields or methods within that component.

To add or edit annotations in an EJB/JPA component:

  1. In the Application Navigator, select the class you want to annotate.

  2. In the Structure window, double-click the member you want to annotate.

    As an alternative, if your class is already open in the Java source editor, put your curser in the location where you intend to insert your annotation.

  3. In the Property Inspector, choose the tab corresponding to your EJB/JPA type.

  4. Choose from any of the annotations available for the specific member you have selected.

12.6.9 Representing Relationships Between Entities

When you create entities from database tables, foreign keys are interpreted as relationships between entities. You can further define these relationships, create new relationships, or map existing relationships to existing tables using the JDeveloper modeling tools. With the modeling tools you can represent relationships as lines between entities, and change the relationships by changing the line configurations. For more information, see Section 23.3, "Modeling EJB/JPA Components on a Diagram.".

12.6.10 Java Persistence Query Language

Java Persistence Query Language (JPQL) offers a standard way to define relationships between entity beans and dependent classes by introducing abstract schema types and relationships in the deployment descriptor. JPQL also defines queries for navigation using abstract schema names and relationships.

The JPAQL query string consists of two mandatory clauses: SELECT and FROM, and an optional WHERE clause. For example:

select d from Departments d where d.department_name = ?1

There are two kinds of methods that use JPQL, finder methods and select methods.

  • Finder methods are exposed to the client and return either a single instance, or a collection of entity bean instances.

  • Select methods are not exposed to the client, they are used internally to return an instance of cmp-field type, or the remote interfaces represented by the cmr-field.

12.6.11 JPA Object-Relational Mappings

The Java Persistence API lets you declaratively map Java objects to relational database tables in a standard, portable way that works both inside a Java EE 5 application server and outside an EJB container. This approach greatly simplifies Java persistence and provides an object-relational mapping approach.

With Oracle TopLink you can configure the JPA behavior of your entities using metadata annotations in your Java source code. At run-time the code is compiled into the corresponding Java class files.

To designate a Java class as a JPA entity, use the @Entity annotation, as shown in Example 12-6.

Example 12-6 Entity Annotation

@Entity
public class Employee implements Serializable {
...
}

You can selectively add annotations to override defaults specified in your deployment descriptors.

For more information on JPA Annotations, see the TopLink JPA Annotation Reference at http://www.oracle.com/technetwork/middleware/ias/toplink-jpa-annotations-096251.html.

12.6.12 How to Use Java Service Facades

A Java service facade implements a lightweight testing environment you can run without an application server.

With EJB 3.0 the Java service facade is similar to an EJB session facade, because you can generate facade methods for entities in the same persistence unit, without the container.

Separating workflow with Java service facades eliminates the direct dependency of the client on the participant JPA objects and promotes design flexibility. Although changes to participants may require changes in the Java service facade, centralizing the workflow in the facade makes such changes more manageable. You change only the Java service facade rather than having to change all the clients. Client code is also simpler because it now delegates the workflow responsibility to the session facade. The client no longer manages the complex workflow interactions between business objects, nor is the client aware of interdependencies between business objects.

You may choose to make the Java service class runnable by generating a sample Java client with a main() method.

Use the JDeveloper Java service facade wizard to create a Java class as a service facade to entities. To create a new Java service facade select the File menu, then New, then Business Tier, then EJB, then Java Service Facade.

You can also create a data control from a service facade. In the Application Navigator, right-click the name of the service facade, then select Create Data Control. From the Bean Data Control Interface Chooser dialog, you can choose to implement oracle.binding.* data control interfaces. The interfaces are TransactionalDataControl, UpdatableDataControl, and ManagedDataControl. For more information, select the Help button in the dialog.

12.7 Implementing Business Processes in Session Beans

A session bean represents a single client inside the application server. To access an application deployed on the server, the client invokes the session bean methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server. A session bean is similar to an interactive session. A session bean is not shared and has only one client, in the same way that an interactive session can have only one user. Like an interactive session, a session bean is not persistent as it does not save data to the database. When the client terminates, its session bean appears to terminate and is no longer associated with the client.

Create your session beans and session bean facades using the JDeveloper Session Bean Wizard. For more information, see Section 12.7.2, "How to Create a Session Bean.".

There are two types of session beans:

12.7.1 Using Session Facades

With JDeveloper you can select to automatically generate your session facade methods any time you create a session bean through the session bean wizard. This creates a session bean that functions as a session facade for your business workflow. For more information, see Section 12.7.2, "How to Create a Session Bean.".

The session facade is implemented as a session bean. The session bean facade encapsulates the complexity of interactions between the business objects participating in a workflow by providing a single interface for the business services of your application.The session facade manages the relationships between numerous BusinessObjects and provides a higher level abstraction to the client.

Session facades can be either stateful or stateless, which you define while creating a session facade in the wizard.

For more information on session facades, see the Oracle Technology Network at http://www.oracle.com/technetwork/java/sessionfacade-141285.html

Use the wizard to automatically implement a session facade when you create a session bean, and to choose the methods you want to implement. Once you've created EJB entities, any session beans you create in the same project are aware of the entities and the methods they expose.

12.7.2 How to Create a Session Bean

Use the session bean wizard to create a new session bean or session facade bean. Or you can create a session bean using the modeling tools.

To create a session bean or session facade using a wizard:

  1. In the Navigator, select File, then New.

  2. In the New Gallery, select Session Bean from the Business Tier category under the EJB folder.

  3. To make the bean a session facade select Generate Session Facade Methods on the EJB Name and Options page.

    Note:

    You must have already created a persistence unit before you can generate a session facade bean. To generate a persistence unit follow the same steps, but select JPA Persistence Unit instead of Session Bean.

  4. Complete the remaining steps in the wizard.

To add or remove session bean facade methods:

  1. In the Application Navigator, select the session bean you want to edit.

  2. Right-click and choose Edit Session Facade.

  3. In the Specify Session Facade Options dialog, check a method expose it through the facade, or unchecked a method so it will not be exposed.

For more information on session facades, see the Core J2EE Pattern Catalog at http://www.oracle.com/technetwork/java/sessionfacade-141285.html.

You can also create a session facade manually by creating a local reference between a session bean and an entity.

To create a local reference:

  1. Create a session bean, if you have not already done so.

  2. Create a local reference between the beans:

    • In the bean class - If you are using EJB 3.0, annotate the bean class to create a reference.

    • Using the EJB Module Editor - If you are using EJB 2.1 (and previous), select an EJB node in the Application Navigator, then double-click Methods in the Structure pane to open the EJB Module Editor. Select EJB Local References.

To create a session bean on an EJB diagram:

  1. Open your EJB diagram.

    If you do not have an EJB diagram, select File, then New, then select EJB Diagram from the Business Tier category.

  2. In the Component Palette, click Session Bean.

    If the Component Palette is not visible, from the View menu, choose Component Palette.

  3. Click inside the EJB diagram (note that you do not drag and drop).

12.7.3 How to Create Session or Message-Driven Beans in Modules

You can create EJBs in both new and existing modules.

To create EJBs in an existing module:

  1. In the Navigator, right-click an EJB module and choose New EJB Session or Message-Driven Bean.

    Or, select the module and choose File menu, then New, then Business Tier, then EJB Session or Message-Driven Bean.

  2. Follow the steps in the wizard.

To create EJBs in a new EJB module:

  1. In the Navigator, select File, then New, then General, then Projects.

  2. In the New Gallery, select the type of project you want to create and click OK.

  3. In the Navigator, right-click on the new project and choose New.

  4. In the New dialog, expand the category for Business Tier.

  5. Click EJB, then Session Bean or Message-Driven Bean.

    Or, select the module and choose File menu, then New, then Business Tier, then EJB Session or Message-Driven Bean.

  6. Click OK.

  7. Follow the steps in the wizard.

12.7.4 How to Add, Delete, and Edit EJB Methods

Once an EJB has been added to your project, you can add, delete, or edit the methods in it. Adding methods as described below ensures that changes are synchronized with remote and home interfaces, when defined.

To add methods (EJB 2.1):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, right-click the Methods node, then choose New EJB Method, then choose the type of method you want to create.

  3. In the Method Details dialog, add details, as necessary.

  4. When finished, click OK.

To add methods (EJB 3.0):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, right-click the EJB, then choose Enterprise Java Beans (EJB), then choose New Method.

  3. In the Bean Method Details dialog, add details, as necessary.

  4. When finished, click OK.

To delete methods (EJB 2.1):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, expand the Methods node.

  3. Right-click the method you want to remove. If you want to remove more than one, select them using Ctrl-click or Shift-click, then right click the selection.

  4. Choose Remove Methods....

  5. Click Yes to confirm.

To delete methods (EJB 3.0):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, double-click the method to locate it in the source file.

  3. In the source file, delete the method.

To edit methods (EJB 2.1):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, expand the Methods node.

  3. Right-click the method you want to edit, then choose Properties.

  4. In the Method Details dialog, edit details, as necessary.

  5. When finished, click OK.

To edit methods (EJB 3.0):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, right-click the EJB, then choose Enterprise Java Beans (EJB), then choose Properties.

  3. In the Bean Method Details dialog, edit details, as necessary.

  4. When finished, click OK.

12.7.5 How to Add a Field to an EJB

You can add fields to EJBs on an EJB diagram or through the EJB Module Editor.

To add a field on an EJB Diagram (EJB 2.1):

  1. Click in the fields compartment (the first compartment) on the EJB in the diagram.

  2. Enter the name of the field and its type.

To add a field using the EJB Module Editor (EJB 2.1):

  1. In the Application Navigator, right-click the EJB to which you want to add a field, then choose Properties.

  2. In the EJB Module Editor, click to expand the EJB, then select Fields.

  3. Click Add.

  4. In the Field Details dialog, add details, as needed.

To add a field (EJB 3.0):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, right-click the EJB, then choose Enterprise Java Beans (EJB) node, then choose New Field.

  3. In the Field Details dialog, add details, as necessary.

  4. When finished, click OK.

12.7.6 How to Remove a Field From an EJB

You can remove fields from EJBs, as described below.

To remove a field on an EJB Diagram:

  1. Click in the fields compartment (the first compartment) on an EJB.

  2. Highlight the field and press the Delete key.

To remove a field using the EJB Module Editor (EJB 2.1):

  1. In the Application Navigator, right-click the node for the EJB to which you want to add a field, then choose Properties.

  2. In the EJB Module Editor, click to expand the EJB, then select Fields.

  3. Select the field you want to remove.

  4. Click Delete.

To remove a field (EJB 3.0):

  1. In the Application Navigator, select an EJB.

  2. In the Structure pane, double-click the field to locate it in the source file.

  3. In the source file, delete the field.

12.7.7 Customizing Business Logic with EJB Environment Entries

Environment entries are name-value pairs that allow you to customize the bean's business logic. Since environment entries are stored in an enterprise bean's deployment descriptor, a bean's business logic can be changed without changing its source code.

For example, an EJB that calculates an order might give a discount depending on the number of items ordered, a certain status (silver, gold, platinum), or for a promotion. Before deploying the bean's application you could assign the discount a certain percentage. When the application runs, a method would call the environment entry to find out the discount value. If you wanted to change that percentage in a different deployment, you would not need to change the source code, you would just need to change the value in the environment entries for the deployment descriptor.

Environment entries are annotated in the source code.

For the complete EJB 3.0 Java Community Process specifications and documentation, see http://www.oracle.com/technetwork/java/docs-135218.html.

12.7.8 Exposing Data to Clients

Depending on how your develop your application, there are different methods of exposing data to clients.

12.7.9 How to Identify Resource References

A resource reference is an element in a deployment descriptor that identifies the component's coded name for the resource. Resource references are used to obtain connector and database connections, and to access JMS connection factories, JavaMail sessions, and URL links.

To add or modify EJB 3.0 resource references:

Go to your source code to annotate resource references.

12.7.10 How to Define a Primary Key for an Entity

A primary key is a unique identifier with one or more persistent attributes. It identifies one instance of a class from all other instances of the same type. Use primary keys to define relationships and to define queries.

Each JPA entity instance must have a primary key. To accommodate your database schema, you can define simple primary keys from persistent fields or composite primary keys from multiple persistent fields. You can also define automatic primary key value generation to simplify your JPA entity implementation.

The simplest way to specify a simple primary key is to use annotations for a single primitive, or JDK object type entity field as the primary key. You can also specify a simple primary key at deployment time using deployment XML.

To configure a simple primary key using annotations:

  1. In your JPA entity implementation, annotate the primary key field using the @Id annotation, as shown in Example 12-7.

    Example 12-7 Configuring Primary Key Using Annotations

    import javax.ejb.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Column;
    
    @Entity
    @Table(name = "EMP")
    public class Employee implements java.io.Serializable {
    private int empNo;
    private String eName;
    private String birthday;
    private Address address;
    private int version;
    
    public Employee() {
    {
    
    @Id
    @Column(name="EMPNO")
    public int getEmpNo() {
    return empNo;
    }
    ...
    }
    
  2. Package and deploy your application.

To configure a simple primary key using deployment XML:

  1. In your JPA entity implementation, implement a primary key field, as shown in Example 12-8.

    Example 12-8 Configuring Primary Key Using Deployment XML

    public class Employee implements java.io.Serializable {
    private int empNo;
    private String eName;
    private String birthday;
    private Address address;
    private int version;
    
    public Employee() {
    {
    
    public int getEmpNo() {
    return empNo;
    }
    ...
    {
    

12.7.11 How to Specify a Primary Key for ADF Binding

For certain ADF Faces features, a designated primary key is required. For example, if you have an ADF Faces table that uses an af:tableSelectMany component, you will need to specify a primary key to be able to implement sorting. When you create EJB/JPA entities from tables (using EJB 3.0), the primary key is specified by default. But if you have to specify a primary key, do the following:

To specify an attribute as primary key:

  1. If you have not already done so, you will need to create an ADF Data Control to create the XML definitions for each entity. For more information, see "Using ADF Model Data Binding in a Java EE Web Application" in Oracle Fusion Middleware Java EE Developer's Guide for Oracle Application Development Framework.

  2. In the Application Navigator, select an EJB entity XML file.

  3. In the Structure pane, select an entity attribute and then from the View menu, choose Property Inspector.

  4. In the Property Inspector, find the attribute you want as the primary key and set the PrimaryKey value to true.

12.7.12 How to Use ADF Data Controls for EJBs

JDeveloper automatically provides a complete set of data control components when you build an ADF Fusion web application. When you build a Java EE application, and/or an EJB project, you assign ADF data controls on your individual session beans. This adds a data control file with the same name as the bean.

For complete details on using ADF data controls for EJBs, see "Using ADF Model Data Binding in a Java EE Web Application" in Oracle Fusion Middleware Java EE Developer's Guide for Oracle Application Development Framework.

12.8 Modeling EJB/JPA Components on a Diagram

For information about modeling EJB and JPA components on a diagram, see Section 23.3, "Modeling EJB/JPA Components on a Diagram.".

12.9 Deploying EJB Modules and JPA Persistence Units

An EJB module is a software unit comprising one or more EJBs, a persistence unit, and an optional EJB deployment descriptor. A JDeveloper project contains only one EJB module. At deploy-time, the module is packaged as an ejb.jar file.

Entity beans were once packaged in the EJB JAR file along with the session and message-driven beans. Today, with JPA entities and the persistence unit technology, at deploy-time, they are packaged in their own JAR file, persistenceunit.jar.

Now your entity beans (JPA entities) are contained separately, in a JPA persistence archive JAR, which includes a persistence.xml file. The JPA persistence unit does not have to be part of the EJB module package, but can be bundled inside the ejb.jar file.

12.9.1 About EJB Modules

JDeveloper project can contain only one EJB module. When you create your first session or message-driven bean in a project, a module is automatically established, if one does not already exist. You are given the option of choosing the EJB version and the persistence manager for your new EJB module.

When you deploy your project you convert the aggregate of session and message-driven beans, plus deployment descriptor into an a EJB JAR file (.jar file), ready for deployment to an application server or as an archive file. By confining the persistence unit to its own JAR file, the persistence unit can easily be reused in other applications. For more information, see Section 9.1, "About Deploying Applications."

12.9.2 About JPA Persistence Units

A JPA persistence unit is comprised of a persistence.xml file, one or more optional orm.xml files, and the managed entity classes that belong to the persistence unit. A persistence unit is a logical grouping of the entity manager, data source, persistent managed classes, and mapping metadata. A persistence unit defines an entity manager's configuration by logically grouping details like entity manager provider, configuration properties, and persistent managed classes.

Each persistence unit must have a name. Only one persistence unit of a given name may exist in a given EJB-JAR, WAR, EAR, or application client JAR. You can package a persistence unit in its own persistence archive and include that archive in whatever Java EE modules require access to it.

The persistence.xml file contains sections or groupings, these groupings correspond to your entities, and run-time data related to the entities. When you create a new entity using the entity wizards, and if you have an existing persistence unit in the project, the entity will be inserted into its own section in the persistence.xml. If you do not have an existing persistence unit, one will be created automatically, with a section included for the entity definitions.

The JAR file or directory, whose META-INF directory contains the persistence.xml file, is called the root of the persistence unit. An EJB 3.0 application that uses entities must define at least one persistence unit root either explicitly or using the OC4J default persistence unit. When you deploy your persistence unit, a JAR file is created called persistenceunit.jar. For more information, see Section 9.1, "About Deploying Applications."

12.9.3 How to Create a JPA Persistence Unit

You can easily create a persistence unit for your entities using the JDeveloper Persistence Unit wizard. Or, when you create a JPA entity, a default persistence unit is created for you, if you do not already have one.

To create a JPA persistence unit:

  1. Select a project in the Application Navigator.

  2. Choose File menu, then New, then Business Tier, then EJB, then JPA Persistence Unit.

  3. Complete the steps in the wizard.

12.9.4 How to Remove EJBs in a Module

To remove an EJB from an EJB module, select the EJB in the System Navigator and press Delete.

12.9.5 How to Import EJBs into JDeveloper

You can import existing EJBs from a JAR file or from a deployment descriptor.

To import an EJB module, or a subset of EJBs within an EJB module into a project:

  1. From the File menu, choose Import.

  2. In the Import dialog, choose EJB JAR (.jar) File.

  3. Follow the steps in the wizard.

To import an EJB deployment descriptor (ejb-jar.xml) file:

  1. From the File menu, choose Import.

  2. In the Import dialog, choose EJB Deployment Descriptor (ejb-jar.xml) File.

  3. Follow the steps in the wizard

    Note:

    If you import a deployment descriptor using this wizard, and then use the wizard to import more files, the wizard caches the last used descriptor file, JAR file, and descriptor source directory in the IDE preferences file for convenience. This makes it easier to do tasks such as splitting an EJB module into multiple modules, importing multiple JAR files residing in the same directory, etc.

To import a WebLogic deployment descriptor (weblogic-ejb-jar.xml) file:

  1. From the File menu, choose Import.

  2. In the Import dialog, choose EJB Deployment Descriptor (ejb-jar.xml) File.

  3. Follow the steps in the wizard

  4. After completing the wizard, in the Navigator, right-click on weblogic-ejb-jar.xml and choose Export to OC4J.

To avoid conflicts, if an EJB with the same name already exists in your existing module, that EJB will not be imported.

12.9.6 How to Modify EJB/ADF Applications to Deploy to Websphere Application Server

NOTE: Could not access this topic in Help Center.

12.10 Running and Testing EJB/JPA Components

To test your EJBs you need to run a client program that can create or find EJB instances and call their remote interface methods. JDeveloper provides a sample client utility that will help you create clients quickly. You can run and test EJBs using either the integrated server or a remote server; the sample client utility can be used to create a client for either type.

12.10.1 How to Test EJB/JPA Components Using the Integrated Server

The integrated Oracle WebLogic Server runs within JDeveloper. You can run and test EJBs quickly and easily using this server, and then deploy your EJBs with no changes to them. You do not need to create a deployment profile to use this server, nor do you have to initialize it.

To run a sample client on the integrated Oracle WebLogic Server:

  1. In the Application Navigator, right-click on an EJB and choose Run.

    Notice in the Message pane that Oracle WebLogic Server has been launched.

  2. Right-click on an EJB and choose Create Sample Java Client from the context menu.

  3. The default choice is to create a client for the integrated Oracle WebLogic Server, so click OK.

    The client is created and opens in the code editor.

    If your session bean serves as a facade over JPA entities, code is generated to instantiate the query methods. If you exposed methods on your bean, the generated client contains methods that can be uncommented to call them.

  4. After your EJB has been successfully started from the Application Navigator, right-click on the sample client and choose Run.

12.10.2 How to Test EJB/JPA Components Using a Remote Server

To test EJBs on a remote server you need to deploy the EJB and then create a sample client. If you deploy first, the framework picks up the deployed applications, which populates the client pick list.

Caution:

You cannot mix different EJB versions in the same module.

To run a sample client on a remote server:

  1. If necessary, create a connection to a running application server. For detailed instructions, see "How to Create a Connection to the Target Application Server."

  2. Create a project-level EJB JAR deployment profile:

    1. In the application navigator, right-click your project node and choose Deploy > New Deployment Profile.

    2. In the Create Deployment Profile dialog, choose a profile type of EJB JAR file and enter a name for the profile. When you click OK the Edit EJB JAR Deployment Profile Properties dialog opens. Accept the defaults and click OK.

  3. Create an application-level, EAR-type deployment profile:

    1. Choose Application > Deploy > New Deployment Profile.

    2. In the Create Deployment Profile dialog, choose a profile type of EAR File and enter a name for the profile. When you click OK the Edit EAR Deployment Profile Properties dialog opens.

  4. Add the new EJB JAR profile to the EAR profile file:

    1. In the Edit EAR Deployment Profile Properties dialog, choose Application Assembly in the navigation pane.

    2. Expand the Java EE Modules tree, and select the EJB JAR profile you created in Step 2 and click OK.

  5. Deploy the application to the application server connection. Choose Application > Deploy application-deployment-profile.

  6. In the [Deploy] dialog box, choose Deploy to Application Server and click Next.

  7. On the Select Server page, choose the application server connection and click Finish. You can track the deployment in the Deployment Log window

  8. In the application navigator, right-click an EJB and choose New Sample Java Client.

  9. In the dialog box, choose to connect to an Application Server Connection. Choose one of the deployed Java EE applications that are listed and click OK.

  10. In the application navigator, right-click the new client and choose Run.

    The Message pane shows you the running output.

12.10.3 How to Test EJB Unit with JUnit

JDeveloper provides support for JUnit regression testing for your EJBs. JUnit is an open source Java regression testing framework that comes as an optional feature in JDeveloper. To use this feature you'll need to install the JUnit extension.

Use JUnit to write and run tests that verify your code. After you install the JUnit extension, you can use the simple wizard to select your session bean or Java class files, to select the methods that you want to test within those files, and then to start the JUnit test.

To run a JUnit test on an EJB:

  1. Install the Junit extension from the JDeveloper Help menu. For more information, see Section 18.12.1, "How to Install JUnit."

  2. Select your EJB session bean or an ordinary Java class (POJO) in the Application Navigator. Or you can navigate to it from within the wizard.

  3. Click File menu, then New, then Business Tier, then EJB, then EJB JUnit TestCase.

  4. Start the JUnit wizard.

  5. Complete the steps in the wizard.

For detailed information about JUnit, visit the JUnit website, http://www.junit.org/.