2 Understanding Enterprise JavaBeans

This chapter describes the new features and programming model of EJB 3.2 and also provides a basic overview EJB components, anatomy, and features.

This chapter includes the following sections:

New Features and Changes in EJB

These sections summarize the changes in the EJB programming model and requirements between EJB 3.2, 3.1 and 3.0, as well between EJB 2.x and 3.x.

What Is New and Changed in EJB 3.2

With Java EE 7, there is a continuing focus on ease of development by offering a simplified application architecture with a cohesive integrated platform; increased efficiency with reduced boiler-plate code and broader use of annotations.

The following summarizes the main new functionality and simplifications made in EJB 3.2 to the earlier EJB APIs:

  • Enhanced Message-driven Beans – Enhanced MDB contract with a no-methods message listener interface to expose all public methods as message listener methods. Also, enhanced the list of standard JMS MDB activation properties.

  • EJB Lite – Extended the EJB Lite Group to include local asynchronous session bean invocations and non-persistent EJB Timer Service. Also defined clear rules for an EJB Lite Container to support other API groups.

  • EJB Timer Enhancements – Enhanced the TimerService API to access all active timers in the EJB module. Also, removed restrictions on javax.ejb.Timer and javax.ejb.TimerHandle that required references to be used only inside a bean.

  • Stateful Session Bean Enhancements – Added an option for the lifecycle callback interceptor methods of stateful session beans to be executed in a transaction context determined by the lifecycle callback method's transaction attribute. Also, introduced an option to disable passivation of stateful session beans.

  • Security Enhancements – Added container provided security role named "**" to indicate any authenticated caller independent of the actual role name. Also, simplified requirements for definition of a security role using the ejb deployment descriptor.

  • Java Persistence 2.1 Support – JPA 2.1 includes new support or enhancements for features including Criteria Bulk Update/Delete, stored procedures, JPQL Generic function, injectable entity listeners, TREAT, converters, DDL generation, and entity graphs. For the complete JPA 2.1 specification, see "JSR-000338 Java Persistence 2.1 (Final Release)" at http://jcp.org/aboutJava/communityprocess/final/jsr338/index.html.

  • Technology Pruning – Support for the following features was made optional in this release:

    • EJB 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence

    • EJB 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence

    • Client View of an EJB 2.1 and earlier Entity Bean

    • EJB QL: Query Language for Container-Managed Persistence Query Methods

For a comprehensive listing of the new features and changes for EJBs in Java EE 7, see the Enterprise JavaBeans 3.2 Specification (JSR-345) at http://jcp.org/en/jsr/summary?id=345.

What Was New and Changed in EJB 3.1

The EJB 3.1 specification provides simplified programming and packaging model changes. The mandatory use of Java interfaces from previous versions has been removed, allowing plain old Java objects to be annotated and used as EJB components. The simplification is further enhanced through the ability to place EJB components directly inside of Web applications, removing the need to produce separate archives to store the Web and EJB components and combine them together in an EAR file.

The following summarizes the new functionality and simplifications made in EJB 3.1 to the earlier EJB APIs:

  • 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 providing local session bean access without requiring a separate local business interface, allowing components to have EJB bean class instances directly injected.

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

  • Embeddable EJB Container – EJB 3.1 supports an embeddable API for executing EJB components within a Java SE environment. Unlike traditional Java EE server-based execution, embeddable usage allows client code and its corresponding enterprise beans to run within the same virtual machine and class loader. This provides better support for testing, offline processing (e.g., batch jobs), and the use of the EJB programming model in desktop applications.

  • JPA 2.1 Support – Oracle EclipseLink is the default JPA 2.1 persistence provider that is shipped with Oracle WebLogic Server. WebLogic Server runs with the JPA 2.1 JAR in the server classpath. Although JPA 2.1 is upwardly compatible with JPA 2.0 and 1.0, JPA 2.1 introduced some methods to existing JPA interfaces that conflict with existing signatures in OpenJPA interfaces.

    As a result, applications that use Kodo/JPA as the persistence provider with earlier releases of WebLogic Server must be recompiled. See Updating Applications to Overcome Conflicts in Developing Enterprise JavaBeans for Oracle WebLogic Server for WebLogic Server 12.1.3. See Configuring the Persistence Provider in Oracle WebLogic Server.

What Was New and Changed in EJB 3.0

The following summarizes the new functionality and simplifications made in EJB 3.0 to the earlier EJB APIs:

  • You are no longer required to create the EJB deployment descriptor files (such as ejb-jar.xml). You can now use metadata annotations in the bean file itself to configure metadata. You are still allowed, however, to use XML deployment descriptors if you want; in the case of conflicts, the deployment descriptor value overrides the annotation value.

  • The only required metadata annotation in your bean file is the one that specifies the type of EJB you are writing (@javax.ejb.Stateless, @javax.ejb.Stateful, @javax.ejb.MessageDriven, or @javax.persistence.Entity). The default value for all other annotations reflect typical and standard use of EJBs. This reduces the amount of code in your bean file in the case where you are programming a typical EJB; you only need to use additional annotations if the default values do not suit your needs.

  • The bean file can be a plain old Java object (or POJO); it is no longer required to implement javax.ejb.SessionBean or javax.ejb.MessageDrivenBean.

  • As a result of not having to implement javax.ejb.SessionBean or javax.ejb.MessageDrivenBean, the bean file no longer has to implement the lifecycle callback methods, such as ejbCreate, ejbPassivate, and so on. If, however, you want to implement these callback methods, you can name them anything you want and then annotate them with the appropriate annotation, such as @javax.ejb.PostActivate.

  • Session beans may expose client views via business interfaces. Session beans may either explicitly implement the business interface or they can specify it using the @javax.ejb.Remote or @javax.ejb.Local annotations.)

  • The business interface is a plain old Java interface (or POJI); it should not extend javax.ejb.EJBObject or javax.ejb.EJBLocalObject.

  • The business interface methods may not throw java.rmi.RemoteException unless the business interface extends java.rmi.Remote.

    Note:

    EJBs with a businesses interface that does not implement java.rmi.Remote are not accessible from wlclient.jar, also known as the IIOP thin client.
  • Bean files supports dependency injection. Dependency injection is when the EJB container automatically supplies (or injects) a variable or setter method in the bean file with a reference to another EJB or resource or another environment entry in the bean's context.

  • Bean files support interceptors, which is a standard way of using aspect-oriented programming with EJB.

    • You can configure two types of interceptor methods: those that intercept business methods and those that intercept lifecycle callbacks.

    • You can configure multiple interceptor methods that execute in a chain in a particular order.

    • You can configure default interceptor methods that execute for all EJBs contained in a JAR file.

Because the EJB 3.x programming model is so simple, Oracle no longer supports using the EJBGen tags and code-generating tool on EJB 3.x beans. Rather, you can use this tool only on 2.x beans. See the EJBGen Reference in Developing Enterprise JavaBeans, Version 2.1, for Oracle WebLogic Server.

Understanding EJB Components

Enterprise JavaBeans (EJB) 3.2 technology is the server-side component architecture for Java EE 7. EJB 3.2 technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.

Session EJBs Implement Business Logic

Session beans implement business logic. There are three types of session beans: stateful, stateless, and singleton. Stateful and stateless session beans serve one client at a time; whereas, singleton session beans can be invoked concurrently.

For detailed information about the types of session beans and when to use them, see "What Is a Session Bean" in the "Enterprise Beans" chapter of the Java EE 7 Tutorial at http://docs.oracle.com/javaee/7/tutorial/index.html.

Stateful Session Beans

Stateful session beans maintain state information that reflects the interaction between the bean and a particular client across methods and transactions. A stateful session bean can manage interactions between a client and other enterprise beans, or manage a workflow.

Example: A company Web site that allows employees to view and update personal profile information could use a stateful session bean to call a variety of other beans to provide the services required by a user, after the user clicks View my Data on a page:

  • Accept the login data from a JSP, and call another EJB whose job it is to validate the login data.

  • Send confirmation of authorization to the JSP.

  • Call a bean that accesses profile information for the authorized user.

Stateless Session Beans

A stateless session bean does not store session or client state information between invocations—the only state it might contain is not specific to a client, for instance, a cached database connection or a reference to another EJB. At most, a stateless session bean may store state for the duration of a method invocation. When a method completes, state information is not retained.

Any instance of a stateless session bean can serve any client—any instance is equivalent. Stateless session beans can provide better performance than stateful session beans, because each stateless session bean instance can support multiple clients, albeit one at a time. The client of a stateless session bean can be a web service endpoint.

Example: An Internet application that allows visitors to click a Contact Us link and send an email could use a stateless session bean to generate the email, based on the to and from information gathered from the user by a JSP.

Singleton Session Beans

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.

Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean 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. Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns.

Example: The Apache Web site provides a Simple Singleton: ComponentRegistry example that demonstrates how a singleton bean uses Container-Managed Concurrency to utilize the Read (@Lock(READ)) functionality, to allow multi-threaded access to the bean, and the Write (@Lock(WRITE)) functionality, to enforce single-threaded access to the bean.

Message-Driven Beans Implement Loosely Coupled Business Logic

A message-driven bean implements loosely coupled or asynchronous business logic in which the response to a request need not be immediate. A message-driven bean receives messages from a JMS Queue or Topic, and performs business logic based on the message contents. It is an asynchronous interface between EJBs and JMS.

Throughout its life cycle, an MDB instance can process messages from multiple clients, although not simultaneously. It does not retain state for a specific client. All instances of a message-driven bean are equivalent—the EJB container can assign a message to any MDB instance. The container can pool these instances to allow streams of messages to be processed concurrently.

The EJB container interacts directly with a message-driven bean—creating bean instances and passing JMS messages to those instances as necessary. The container creates bean instances at deployment time, adding and removing instances during operation based on message traffic.

For detailed information, see Developing Message-Driven Beans for Oracle WebLogic Server.

Example: In an on-line shopping application, where the process of taking an order from a customer results in a process that issues a purchase order to a supplier, the supplier ordering process could be implemented by a message-driven bean. While taking the customer order always results in placing a supplier order, the steps are loosely coupled because it is not necessary to generate the supplier order before confirming the customer order. It is acceptable or beneficial for customer orders to "stack up" before the associated supplier orders are issued.

EJB Anatomy and Environment

These sections briefly describe classes required for each bean type, the EJB run-time environment, and the deployment descriptor files that govern a bean's run-time behavior.

EJB Components

Every bean type requires a bean class. Table 2-1 defines the supported client views that make up each type of EJB, and defines any additional required classes.

Note:

The EJB 2.1 and earlier API required that Local and Remote clients access the stateful or stateless session bean by means of the session bean's local or remote home and the local or remote component interfaces. These interfaces remain available for use with EJB 3.x; however, the EJB 2.1 Remote and Local client view is not supported for singleton session beans.

See Create EJB Classes and Interfaces in Developing Enterprise JavaBeans, Version 2.1, for Oracle WebLogic Server.

Table 2-1 Supported Client Views in EJB 3.2

Client Views Session Bean Types Additional Required Classes

Remote Client

Stateful, Stateless, and Singleton session beans

Remote business interface that defines the bean's business and lifecycle methods.

Local Client

Stateful, Stateless, and Singleton session beans

Local business interface that defines the bean's business and lifecycle methods.

Local No- interface

Stateful, Stateless, and Singleton session beans

Only requires the bean class.

Web Service Clients

Stateless and Singleton session beans

A Web service endpoint that is accessed as a JAX-WS or JAX-RPC service endpoint using the JAX-WS or JAX-RPC client view APIs.

The EJB Container

An EJB container is a run-time container for beans that are deployed to an application server. The container is automatically created when the application server starts up, and serves as an interface between a bean and run-time services such as:

  • Life cycle management

  • Code generation

  • Security

  • Transaction management

  • Locking and concurrency control

EJB Metadata Annotations

The WebLogic Server EJB 3.2 programming model uses the Java EE 7 metadata annotations feature in which you create an annotated EJB 3.2 bean file, and then compile the class with standard Java compiler, which can then be packaged into a target module for deployment. At runtime, WebLogic Server parses the annotations and applies the required behavioral aspects to the bean file.

See Programming the Annotated EJB Class.

Optional EJB Deployment Descriptors

As of EJB 3.0, you are no longer required to create the EJB deployment descriptor files (such as ejb-jar.xml). However, you can still use XML deployment descriptors if you want. In the case of conflicts, the deployment descriptor value overrides the annotation value.

If you are continuing to use deployment descriptors in your EJB implementation, refer to EJB Deployment Descriptors in Developing Enterprise JavaBeans, Version 2.1, for Oracle WebLogic Server.

The WebLogic Server EJB container supports three deployment descriptors:

  • ejb-jar.xml—The standard Java EE deployment descriptor. The ejb-jar.xml may be used to define EJBs and to specify standard configuration settings for the EJBs. An ejb-jar.xml can specify multiple beans that will be deployed together.

  • weblogic-ejb-jar.xml—WebLogic Server-specific deployment descriptor that contains elements related to WebLogic Server features such as clustering, caching, and transactions. This file is required if your beans take advantage of WebLogic Server-specific features. Like ejb-jar.xml, weblogic-ejb-jar.xml can specify multiple beans that will be deployed together.

  • weblogic-cmp-jar.xml—WebLogic Server-specific deployment descriptor that contains elements related to container-managed persistence for entity beans. Entity beans that use container-managed persistence must be specified in a weblogic-cmp-jar.xml file.

For descriptions of the WebLogic Server EJB deployment descriptors, refer to Deployment Descriptor Schema and Document Type Definitions Reference in Developing Enterprise JavaBeans, Version 2.1, for Oracle WebLogic Server.

EJB Clients and Communications

An EJB can be accessed by server-side or client-side objects such as servlets, Java client applications, other EJBs, web services, and non-Java clients. Any client of an EJB, whether in the same or a different application, accesses it in a similar fashion. WebLogic Server automatically creates implementations of an EJB's remote home and remote business interfaces, which can function remotely.

Accessing EJBs

Clients access enterprise beans either through a no-interface view or through a business interface. A no-interface view of an enterprise bean exposes the public methods of the enterprise bean implementation class to clients. Clients using the no-interface view of an enterprise bean may invoke any public methods in the enterprise bean implementation class or any super-classes of the implementation class. A business interface is a standard Java programming language interface that contains the business methods of the enterprise bean.

The client of an enterprise bean obtains a reference to an instance of an enterprise bean through either dependency injection, using Java programming language annotations, or JNDI lookup, using the Java Naming and Directory Interface syntax to find the enterprise bean instance.

Dependency injection is the simplest way of obtaining an enterprise bean reference. Clients that run within a Java EE server-managed environment, JavaServer Faces web applications, JAX-RS web services, other enterprise beans, or Java EE application clients, support dependency injection using the javax.ejb.EJB annotation.

Applications that run outside a Java EE server-managed environment, such as Java SE applications, must perform an explicit lookup. JNDI supports a global syntax for identifying Java EE components to simplify this explicit lookup. For more information see, Using the JNDI Portable Syntax.

Because of network overhead, it is more efficient to access beans from a client on the same machine than from a remote client, and even more efficient if the client is in the same application.

For information on programming client access to an EJB, see "Accessing Enterprise Beans" in the "Enterprise Beans" chapter of the Java EE 7 Tutorial at http://docs.oracle.com/javaee/7/tutorial/index.html.

EJB Communications

WebLogic Server EJBs use:

  • T3—To communicate with remote objects. T3 is a WebLogic-proprietary remote network protocol that implements the Remote Method Invocation (RMI) protocol.

  • RMI—To communicate with remote objects. RMI enables an application to obtain a reference to an object located elsewhere in the network, and to invoke methods on that object as though it were co-located with the client on the same JVM locally in the client's virtual machine. An EJB with a remote interface is an RMI object. For more information on WebLogic RMI, see Developing RMI Applications for Oracle WebLogic Server.

  • HTTP—An EJB can obtain an HTTP connection to a Web server external to the WebLogic Server environment by using the java.net.URL resource connection factory. See Configuring EJBs to Send Requests to an URL in Developing Enterprise JavaBeans, Version 2.1, for Oracle WebLogic Server.

You can specify the attributes of the network connection an EJB uses by binding the EJB to a WebLogic Server custom network channel. See Configuring Network Resources in Administering Server Environments for Oracle WebLogic Server.

Securing EJBs

By default, any user can invoke the public methods of an EJB. Therefore, if you want to restrict access to the EJB, you can use security-related annotations to specify the roles that are allowed to invoke all, or a subset, of the methods, which is explained in Securing Access to the EJB.

In addition, you create security roles and map users to roles using the WebLogic Server Administration Console to update your security realm. See Manage Security Roles in the Oracle WebLogic Server Administration Console Online Help.

For additional information about security and EJBs, see: