Fusion Middleware Documentation
Advanced Search


Developing Applications with Oracle JDeveloper
Close Window

Table of Contents

Show All | Collapse

19 Developing with EJB and JPA Components

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

This chapter includes the following sections:

19.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.

19.2 Support For EJB Versions and Features

JDeveloper supports EJB 3.x, as well as versions 1.0 through 2.1. However, the EJB wizards do not support the creation of EJBs earlier than version 2.x, but will instead prompt you to import such older EJBs into version 3.1. The current JDeveloper documentation, including this chapter of the User Guide and the embedded online help, focus on EJB 3.1 development tasks.

Note:

Previous versions of the JDeveloper 10g documentation tell how to work with EJB 2.1 and earlier. 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 EJB 3.1 specification and documentation, refer to the "Java Platform, Enterprise Edition (Java EE) Technical Documentation" page at http://docs.oracle.com/javaee/.

Note:

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

Supported New EJB 3.1 Features

The EJB 3.1 specification provides simplified programming and packaging model changes.

  • Singleton Session Bean – Singleton session beans provide a formal programming construct that guarantees a session bean will be instantiated once per application in a particular Java Virtual Machine (JVM), and that it will exist for the life cycle of the application. With singletons, you can easily share state between multiple instances of an enterprise bean component or between multiple enterprise bean components in the application.

  • Simplified No Interface Client View – The No-interface local client view type simplifies EJB development by making local business interfaces optional. A bean that does not have a local business interface exposes a no-interface view, which provides the same enterprise bean functionality without having to write a separate business interface.

  • Packaging and Deploying EJBs Directly in a WAR File – EJB 3.1 provides the ability to place EJB components directly inside of Web application archive (WAR) files, removing the need to produce archives to store the Web and EJB components and combine them together in an enterprise application archive (EAR) file.

  • Portable Global JNDI Names – The Portable Global JNDI naming option in EJB 3.1 provides a number of common, well-known namespaces in which EJB components can be registered and looked up from using the pattern java:global[/<app-name>]/<module-name>/<bean-name>. This standardizes how and where EJB components are registered in JNDI, and how they can be looked up and used by applications.

  • Asynchronous Session Bean Invocations – An EJB 3.1 session bean can expose methods with asynchronous client invocation semantics. Using the @Asynchronous annotation in an EJB class or specific method will direct the EJB container to return control immediately to the client when the method is invoked. The method may return a future object to allow the client to check on the status of the method invocation, and retrieve result values that are asynchronously produced.

  • EJB Timer Enhancements – The EJB 3.1 Timer Service supports calendar-based EJB Timer expressions. The scheduling functionality takes the form of CRON-styled schedule definitions that can be placed on EJB methods, in order to have the methods be automatically invoked according to the defined schedule. EJB 3.1 also supports the automatic creation of a timer based on metadata in the bean class or deployment descriptor, which allows the bean developer to schedule a timer without relying on a bean invocation to programmatically invoke one of the Timer Service timer creation methods. Automatically created timers are created by the container as a result of application deployment.

Supported New and Changed EJB 3.0 Features

The key differences between EJB 3.0 and previous versions are:

  • Simplified EJBs - EJB 3.0 eliminated the need for home and component interfaces and the requirement for bean classes for implementing javax.ejb.EnterpriseBean interfaces. The EJB bean class can be a pure Java class (POJO), and the interface can be a simple business interface. The bean class implements the business interface.

  • Use of Annotations Instead of Deployment Descriptors - Metadata annotation is an alternative to deployment descriptors. Annotations specify bean types, different attributes such as transaction or security settings, O-R mapping and injection of environment or resource references. Deployment descriptor settings override metadata annotations.

  • Dependency Injection - The API for lookup and use of EJB environment and resource references was simplified, and dependency injection is used instead. Metadata annotation is used for dependency injection.

  • Enhanced Lifecycle Methods and Callback Listener Classes - Unlike previous versions of EJB, you do not have to implement all unnecessary callback methods. Instead, you designate any arbitrary method as a callback method to receive notifications for lifecycle events. A callback listener class is used instead of callback methods defined in the same bean class.

  • Interceptors - An interceptor is a method that intercepts a business method invocation. An interceptor method is defined in a stateless session bean, stateful session bean, or a message-driven bean. An interceptor class is used instead of defining the interceptor method in the bean class.

  • Simple JNDI Lookup of EJB - Lookup of EJB is simplified and clients do not have to create a bean instance by invoking a create() method on EJB and can now directly invoke a method on the EJB.

Session Beans

  • Simplified Beans - Session beans are pure Java classes and do not implement javax.ejb.SessionBean interfaces. The home interface is optional. A session bean has either a remote, local, or both interfaces and these interfaces do not have to extend EJBObject or EJBLocalObject.

  • Metadata Annotations - Metadata annotations are used to specify the bean or interface and run-time properties of session beans. For example, a session bean is marked with @Stateless or @Stateful to specify the bean type.

  • Lifecycle Methods and Callback Listeners - Callback listeners are supported with both stateful and stateless session beans. These callback methods are specified using annotations or a deployment descriptor.

  • Dependency Injection - Dependency injection is used either from stateful or stateless session beans. Developers can use either metadata annotations or deployment descriptors to inject resources, EJB context or environment entries.

  • Interceptors - Interceptor methods or interceptor classes are supported with both stateful and stateless session beans.

Message-Driven Beans (MDBs)

  • Simplified Beans - Message-driven beans do not have to implement the javax.ejb.MessageDriven interface; they implement the javax.jms.MessageListener interface.

  • Metadata Annotations - Metadata annotations are used to specify the bean or interface and run-time properties of MDBs. For example, an MDB is marked with @MessageDriven for specifying the bean type.

  • Lifecycle Methods and Callback Listeners - Callback listeners are supported with MDBs. These callback methods are either specified using annotations or the deployment descriptor.

  • Dependency Injection - Dependency injection is used from an MDB. You either use metadata annotations or deployment descriptors to inject resources, EJB context, or environment entries used by an MDB.

  • Interceptors - Interceptor methods or interceptor classes can be used with MDBs.

Entities - Java Persistence API (JPA)

  • Simplified Beans (POJO Persistence) - EJB 3.0 greatly simplified entity beans and standardizes the POJO persistence model. Entity beans are concrete Java classes and do not require any interfaces. The entity bean classes support polymorphism and inheritance. Entities can have different types of relationships, and container-managed relationships are manually managed by the developer.

  • Entity Manager API - EJB 3.0 introduced the EntityManager API that is used to create, find, remove, and update entities. The EntityManager API introduces the concept of detachment/merging of entity bean instances similar to the Value Object Pattern. A bean instance may be detached and may be updated by a client locally and then sent back to the entity manager to be merged and synchronized with the database.

  • Metadata Annotations - Metadata annotations greatly simplified development of entities by removing the requirement of deployment descriptors. The entity annotation is used to specify a class to be an entity bean. Annotations are used to specify transaction attributes, security permissions, callback listeners and annotated queries.

  • Query Language Enhancements - EJB 3.0 greatly improved the query capability for entities with Java Persistence Query Language (JPQL). JPQL enhances EJB-QL by providing additional operations such as bulk updates and deletes, JOIN operations, GROUP BY HAVING, projection and sub-queries. Also dynamic queries can be written using EJB QL.

  • Lifecycle Methods and Callback Listeners - Callback listeners are supported with entity beans. Callback methods are either specified using annotations or a deployment descriptor.

19.3 Building EJB 3.x 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.

19.3.1 EJB 3.x Application Development Process

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

19.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 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 19.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 using O-R mapping metadata, you have more control over the mapping, but you must code the annotations by hand. For more information, see Section 19.6.1.2, "Metadata Annotations for O-R Mapping".

19.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 19.7, "Implementing Business Processes in Session Beans" and Section 19.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 Applications window and choosing Edit Session Facade.

19.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 19.10, "Deploying EJB Modules and JPA Persistence Units".

19.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 19.11.2, "How to Test EJB/JPA Components Using a Remote Server".

19.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 Data Controls" in Developing Applications with Oracle ADF Data Controls.

19.4 How to Work with an EJB Business Services Layer

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

To create a web-based application:

  • Select File > New > Application.

    The General category in the New Gallery provides a list of available applications. For EJB projects you can choose to build either a custom application or the Java EE Web application. The Java EE Web Application creates an EJB/JPA data-bound web application.

    Tip: Frequently-used selections are automatically saved to the New menu for easy access.

To create JPA entities:

  1. In the Applications window, right-click the project in which you want to create a JPA entity and choose New.

  2. In the New Gallery, expand Business Tier, select EJB and then select Entity or Entities from Tables and click OK.

    Tip: Frequently-used selections are automatically saved to the New menu for easy access.

  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 Entity or Entities from Tables wizard to create JPA entities.

    For more information at any time, press F1 or click Help from within the wizard.

To implement a session facade:

  1. In the Applications window, right-click the project in which you want to create a session facade and choose New.

  2. In the New Gallery, expand Business Tier, select EJB and then select Java Service Facade (JPA/Toplink) and click OK.

    Tip: Frequently-used selections are automatically saved to the New menu for easy access.

  3. Follow the steps in the Java Service Facade 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.

    For more information at any time, press F1 or click Help from within the wizard.

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

  • Right-click your session bean in the Applications window and choose Create Data Control.

    This creates a file called DataControls.dcx which contains information to initialize the data control to work with your session bean.

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.

19.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:

  • MVC - The MVC pattern divides an application into three parts, the Model, View, and Controller. The model represents the business services of the application, the view is the portion of the application that the client accesses, the controller controls the flows and actions of the application and provides seamless interaction between the model and view. The MVC pattern is automatically implemented if you choose the Fusion Web Application (ADF) or Java EE Web Application template when you begin your project.

  • Session Facade - The session facade pattern contains and centralizes complex interactions between lower-level EJBs (often JPA entities). It provides a single interface for the business services of your application. For more information, see Section 19.7, "Implementing Business Processes in Session Beans".

  • Business Delegate - The business delegate pattern decouples clients and business services, hiding the underlying implementation details of the business service. The business delegate pattern is implemented by the data control, which is represented in JDeveloper by the Data Control Palette. For more information, see "Using ADF Data Controls" in Developing Applications with Oracle ADF Data Controls.

19.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.x is defined in the Java Persistence API.

19.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

19.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 19-1 contains the source code for a simple JPA entity.

Example 19-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.

19.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 19-2.

Example 19-2 Mapping Annotations

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

19.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 19-3 contains code that uses the joined sub class strategy.

Example 19-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 
{
...
}

19.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 19-4.

Example 19-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); 
}
}

19.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 19.6.7, "Annotations for EJB/JPA".

19.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 an application server data sources.

Note:

When running the Entity Beans from Tables wizard, if you configure the Attach an ID generator to each generated entity... field on the General Options page, you will need to manually configure the ID generator for the @SequenceGenerator or the @SequenceGenerator option, depending on which one you select. For additional instructions, refer to the Javadoc generated into each entity class.

To create entities or entities from tables:

  1. From the main menu, choose File > New.

  2. In the New Gallery, expand Business Tier, select EJB and then select Entity or Entities from Tables and click OK.

    Tip: Frequently-used selections are automatically saved to the File menu for easy access.

  3. Follow the steps in the Create Entities from Tables or Create Entity wizard to create JPA entities.

    For more information at any time, press F1 or click Help from within the wizard.

To create EJBs in an existing project:

  1. In the Applications window, select the project in which you want to create a JPA entity and choose New.

  2. In the New Gallery, expand Business Tier, select EJB and then select Entity or Entities from Tables and click OK.

    Or, from the main menu, choose File > New to open the New Gallery, and then follow step 2.

    Tip: Frequently-used selections are automatically saved to the File menu for easy access.

  3. Follow the steps in the Create Entities from Tables or Create Entity wizard.

To create EJBs in a new project:

  1. From the main menu, choose File > New > Projects.

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

  3. In the Applications window, right-click the new project and choose New (or select the project and on the main menu choose File > New).

    In the New Gallery, expand Business Tier, select EJB and then select Entity or Entities from Tables and click OK.

    Tip: Frequently-used selections are automatically saved to the File menu for easy access.

19.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 Developing Fusion Web Applications with Oracle Application Development Framework.

The SDO architecture supported by JDeveloper offers the following:

  • Simplifies the Java EE 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 Java EE 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 beans.

19.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 19.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/sdo

19.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 Java EE 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 19.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.

19.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 19-5 to the weblogic-application.xml which by default is located in <workspace-directory>/src/META-INF.

Example 19-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.

19.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.

19.6.6 How to Generate Database Tables from JPA Entities

When you deploy a JPA entity to 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 19.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 19.10, "Deploying EJB Modules and JPA Persistence Units.".

19.6.7 Annotations for EJB/JPA

Annotations simplify your development tasks by reducing the number of deployment descriptors needed for your application components. Annotations are also 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.x, see http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

Note:

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

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

19.6.7.1 EJB 3.x

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 Singleton Session Bean. Choose TRUE or FALSE to annotate your class as a singleton session bean.

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

19.6.7.2 JPA 2.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 Properties window displays a different set of contextual options, which you can use to add or edit annotations for the various members within the component class.

19.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 Properties window.

Note:

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

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

  1. In the Applications window, 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 Properties window, 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 Properties window 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 Properties window.

Note:

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

Once your Java class is transformed into an EJB/JPA component using a class-level annotation, use the Properties window 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 Applications window, 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 Properties window, choose the tab corresponding to your EJB/JPA type.

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

19.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 5.7, "Modeling EJB/JPA Components.".

19.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.

19.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 19-6.

Example 19-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.

19.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.x, 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, from the main menu, select File > New, then in the New Gallery, expand Business Tier and select EJB, and then Java Service Facade and click OK.

You can also create a data control from a service facade. In the Applications window, 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.

19.6.13 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 the mapping descriptor XML (orm.xml file).

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 19-7.

    Example 19-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 entity mappings using a mapping descriptor (orm.xml):

Create a mapping file (orm.xml) for the persistence unit.

  1. Open the persistence.xml file in the Overview editor.

  2. Select the General tab, expand the JPA Mapping Descriptors section, and click Create New JPA Mapping Descriptor.

  3. Open the orm.xml file in the Overview editor.

  4. To add the desired entity, select the General tab, then select Mapped Classes, then Entities, and then click the + button.

    The orm.xml file is created and an entry is added for a single entity. When adding mappings to that entity, you will now be prompted to save those mappings using either annotations or XML (or both).

Configuring ID mapping in an orm.xml file

  1. In the Overview editor, double click the orm.xml file you created in To configure entity mappings using a mapping descriptor (orm.xml):.

  2. In the Structure pane, expand it until you have reached your entity. Then right-click the desired ID field and choose Map As -> ID. When prompted, choose XML to persist the metadata in the orm.xml file, which should look similar to the one shown in Example 19-8.

    Example 19-8 Configuring Primary Key Using Mapping XML

    <?xml version="1.0" encoding="windows-1252" ?>
    <entity-mappings xmlns="<a target="_blank" href="http://www.eclipse.org/eclipselink/xsds/persistence/orm"">http://www.eclipse.org/eclipselink/xsds/persistence/orm"</a>
                     xmlns:xsi="<a target="_blank" href="http://www.w3.org/2001/XMLSchema-instance"">http://www.w3.org/2001/XMLSchema-instance"</a>
                     xsi:schemaLocation="<a target="_blank" href="http://www.eclipse.org/eclipselink/xsds/persistence/orm">http://www.eclipse.org/eclipselink/xsds/persistence/orm</a> <a target="_blank"                  href="http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd"">http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd"</a>
                     version="2.4">
      <entity class="model1.Departments">
        <attributes>
          <id name="departmentId"/>
        </attributes>
      </entity>
    </entity-mappings>
    

19.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 19.7.2, "How to Create a Session Bean.".

There are three types of session beans:

  • Stateful. A stateful session bean maintains conversational state on behalf of the client. A conversational state is defined as the session bean field values plus all objects reachable from the session bean fields. Stateful session beans do not directly represent data in a persistent data store, but they access and update data on behalf of the client. The lifetime of a stateful session bean is typically that of its client.

  • Stateless. Stateless session beans are designed strictly to provide server-side behavior. They are anonymous because they contain no user-specific data. The EJB architecture provides ways for a single stateless session bean to serve the needs of many clients. All stateless session bean instances are equivalent when they are not involved in serving a client-invoked method. The term stateless means that it does not have any state information for a specific client. However, stateless session beans can have non-client specific state, for example, an open database connection.

  • Singleton. Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean instance per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints. With singletons, you can easily share state between multiple instances of an enterprise bean component or between multiple enterprise bean components in the application. Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns.

19.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 Create Session Bean wizard. This creates a session bean that functions as a session facade for your business workflow. For more information, see Section 19.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 stateful, stateless, or singleton, 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.

19.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. From the main menu, choose File > New.

  2. In the New Gallery, expand Business Tier, select EJB and then select Session Bean and click OK.

    Tip: Frequently-used selections are automatically saved to the File menu for easy access.

    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.

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

    For more information at any time, press F1 or click Help from within the wizard.

  4. Complete the remaining steps in the Create Session Bean wizard.

To add or remove session bean facade methods:

  1. In the Applications window, select the session bean you want to edit.

  2. Right-click and choose Edit Session Facade.

  3. In the Specify Session Facade Options dialog, select a method on the list to expose it through the facade, or deselect 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.x, 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 Applications window, 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. From the Applications window, open your EJB diagram.

    If you do not have an EJB diagram, from the main menu, select File > New. In the New Gallery, expand Business Tier, select EJB Diagram and then click OK.

  2. In the Components window, click Session Bean.

    If the Components window is not visible, from the View menu, choose Components.

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

19.7.3 How to Create Session Beans in EJB Modules

You can create session beans in both new and existing EJB modules.

To create session beans in an existing EJB module:

  1. In the Applications window, right-click an EJB project and choose New > Session Bean.

    Or, select the project and on the main menu choose File > New > From Gallery. In the New Gallery, expand Business Tier, select EJB, and then select Session Bean and click OK.

  2. Follow the steps in the Create Session Bean wizard.

To create session beans in a new EJB module:

  1. In the Applications window, select File > New > Project.

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

  3. In the Applications window, right-click the new project and choose New > From Gallery. In the New Gallery, expand the category for Business Tier, select EJB, and then select Session Bean and click OK.

    Or, select the project, and choose New > Session Bean.

  4. Follow the steps in the Create Session Bean wizard.

19.7.4 How to Create Message-Drive Beans in EJB Modules

You can create EJBs in both new and existing modules.

To create message-driven beans in an existing EJB module:

  1. In the Applications window, right-click an EJB project and choose New > Message-Driven Bean.

    Or, select the project and on the main menu choose File > New > From Gallery. In the New Gallery, expand Business Tier, select EJB, and then select Message-Driven Bean and click OK.

  2. Follow the steps in the Create Message-Driven Bean wizard.

To create message-driven beans in a new EJB module:

  1. In the Applications window, select File > New > Project.

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

  3. In the Applications window, right-click the new project and choose New > From Gallery. In the New Gallery, expand the category for Business Tier, select EJB, and then select Message-Driven Bean and click OK.

    Or, select the project, and choose New > Message-Driven Bean.

  4. Follow the steps in the Create Message-Driven Bean wizard.

19.7.5 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:

  1. In the Applications window, 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:

  1. In the Applications window, 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:

  1. In the Applications window, 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.

19.7.6 How to Add a Field to an EJB

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

  1. In the Applications window, 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.

19.7.7 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 Applications window:

  1. In the Applications window, 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.

19.7.8 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.x Java Community Process specifications and documentation, see http://www.oracle.com/technetwork/java/docs-135218.html.

19.7.9 Exposing Data to Clients

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

19.7.10 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.x resource references:

Go to your source code to annotate resource references.

19.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.x), 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. Create an ADF Data Control to create the XML definitions for each entity. For more information, see "Using ADF Data Controls" in Developing Applications with Oracle ADF Data Controls.

  2. In the Applications window, select an EJB entity XML file.

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

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

19.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 more information, see "Using ADF Data Controls" in Developing Applications with Oracle ADF Data Controls.

19.8 Modeling EJB/JPA Components on a Diagram

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

19.9 Deploying EJBs as Part of an Web Application

EJB 3.1 has removed the restriction that enterprise bean classes must be packaged in an ejb-jar file. Therefore, EJB classes can be packaged directly inside a Web application archive (WAR) using the same packaging guidelines that apply to Web application classes. Simply put your EJB classes in the WEB-INF/classes directory or in a JAR file within WEB-INF/lib directory. Optionally, if you are also using the EJB deployment descriptor, you can package it as WEB-INF/ejb-jar.xml.

19.10 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.

19.10.1 Deploying JPA Entity Beans

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

This way 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.

19.10.2 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."

19.10.3 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.x application that uses entities must define at least one persistence unit root either explicitly or using the JDeveloper 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."

19.10.4 How to Create a JPA Persistence Unit

You can create a persistence unit for your entities using the 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 Applications window and from the File menu, choose New > From Gallery.

  2. From the New Gallery, expand Business Tier and EJB, and then select JPA Persistence Unit and click OK.

  3. Complete the steps in the New Persistence Unit wizard.

19.10.5 How to Remove EJBs in a Module

To remove an EJB from an EJB module, select the EJB in the Applications window and press Delete.

19.10.6 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 Import 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 Import 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 Import wizard.

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

19.11 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.

19.11.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 session bean client on the integrated Oracle WebLogic Server:

  1. In the Applications window, right-click a session bean and choose Run.

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

  2. Right-click a session bean 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 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 bean has been successfully started from the Applications window, right-click the sample client and choose Run.

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

Before you can successfully run a sample MDB client on the integrated Oracle WebLogic Server, you must first create a corresponding JMS queue resource in the WebLogic Server domain.

  1. Follow the JMS "Queue and Topic Destination Configuration" instructions in Administering JMS Resources for Oracle WebLogic Server.

  2. Use the following guidelines when creating your JMS module resources:

    1. Create a new test JMS module (for example, "TestJmsModule") with a new queue resource (for example, "DefaultQueue"), and

    2. Use a JNDI name that matches your generated MDB's Mapped Name, such as "weblogic.wsee.DefaultQueue".

    3. Add a default subdeployment resource, (for example, "DefaultQueue") and target it to the JMS server that is associated with the domain's DefaultServer instance.

  3. Follow the steps in "To run a sample session bean client on the integrated Oracle WebLogic Server:", but in Applications window, select your MDB to create and run the sample client.

19.11.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 Applications window, 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 Applications window, 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 Applications window, right-click the new client and choose Run.

    The Message pane shows you the running output.

19.11.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 13.4.1, "How to Install JUnit."

  2. Right-click the EJB session bean or an ordinary Java class (POJO) in the Applications window (or you can navigate to it from within the wizard) and choose New > From Gallery.

  3. From the New Gallery, expand Business Tier and EJB, and then select EJB JUnit TestCase and click OK.

  4. Start the JUnit wizard.

  5. Complete the steps in the wizard.