P. 1
Java Certification Success, Part 3: SCBCD

Java Certification Success, Part 3: SCBCD

|Views: 341|Likes:
Published by vivekagar

More info:

Published by: vivekagar on Dec 31, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

10/22/2011

pdf

text

original

Sections

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials
ibm.com/developerWorks

Table of contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.

1. Getting started ....................................................................................... 2 2. EJB overview......................................................................................... 4 3. Client view of a session bean .............................................................. 12 4. Session bean component contract ...................................................... 20 5. Session bean lifecycle ......................................................................... 31 6. Client view of an entity......................................................................... 38 7. Component contract for CMP .............................................................. 46 8. CMP entity bean lifecycle .................................................................... 55 9. Entity beans......................................................................................... 63 10. EJB-QL .............................................................................................. 70 11. MDB component contract .................................................................. 77 12. Transactions ...................................................................................... 84 13. Exceptions ......................................................................................... 91 14. Enterprise bean environment ............................................................ 98 15. Security management...................................................................... 106 16. Wrap-up and resources ................................................................... 113

Java certification success, Part 3: SCBCD

Page 1 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 1. Getting started Before you start
The Sun Certified Business Component Developer (SCBCD) for the Java 2 Platform, Enterprise Edition 1.3 Exam is for anyone using J2EE technologies to develop server-side components that encapsulate the business logic of an application. Passing the exam demonstrates an expert level of understanding of the Enterprise JavaBeans (EJB) 2.0 architecture, technology features, and application development lifecycle. The exam was launched worldwide on August 25, 2003. The SCBCD certification requires you to be a Sun Certified Programmer for the Java platform (any edition).

Should I take this tutorial?
The exam is intended for EJB professionals who have at least some experience developing and deploying server-side applications using EJB 2.0 components. This tutorial comprehensively covers the core concepts that are tested in the SCBCD exam; however, it is not intended to serve as an introduction to EJB technology. It focuses precisely on what you need to know to be successful in the exam. The 14 exam objectives mainly deal with EJB technology basics, lifecycle and behavior of different bean types, how the clients interact with the beans, container-managed persistence (CMP), transactions, and security management. The tutorial is organized according to the exam objectives, with each section dedicated to a corresponding exam objective. In addition, we've provided example code wherever necessary, and at the end of each section, we have provided sample exam questions, which test the concepts discussed under that objective. Each question includes detailed explanations about why a choice is correct or incorrect. In every section, you must devote special attention to the responsibilities of different EJB roles, such as Bean Provider, Application Assembler, and Deployer. For the exam, you need to know which role has the primary responsibility for different tasks in the EJB application lifecycle.

Page 2 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

About the authors
Seema Manivannan has a Bachelor of Technology degree in Electrical and Electronics Engineering and a PG in Advanced Computing from C-DAC. Her work experience includes software development, teaching, and content development in Java programming and related technologies. She holds SCJP, SCWCD, and SCBCD certifications. Seema has been with Whizlabs for over two years, where she has co-authored the Sun certification exam simulators. She is an experienced corporate trainer and conducts instructor-led online training for the SCJP, SCWCD, and SCBCD certification exams for Whizlabs. She is also the moderator of the Whizlabs SCBCD discussion forum. You can reach her at seema@whizlabs.com. Pradeep Chopra is the cofounder of Whizlabs Software (http://www.whizlabs.com/) , a global leader in IT skill assessment and certification exam preparation. A graduate of the Indian Institute of Technology, Delhi, Pradeep has been consulting individuals and organizations across the globe on the values and benefits of IT certifications. You can reach him at pradeep@whizlabs.com.

Java certification success, Part 3: SCBCD

Page 3 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 2. EJB overview Introduction
Enterprise JavaBeans (EJB) architecture is a server-side distributed component model, which follows the "Write Once, Run Anywhere" philosophy of the Java platform. EJB applications can be written once and then deployed on any EJB-compliant server without any source code changes or recompilation. The runtime behavior of the enterprise bean can be customized through the deployment descriptor itself. Enterprise beans typically contain the business logic of enterprise applications. The EJB container provides services, such as security checks, resource pooling, networking, thread safety, transactions, persistence, and lifecycle management, thus allowing the developer to concentrate entirely on the business logic.

Types of enterprise beans
The three types of enterprise beans are session beans, entity beans, and message-driven beans (MDBs). Session beans represent a process executing on behalf of a single client. Even though it does not directly represent shared data, it can access or update data in a database. Session beans can be stateful or stateless. A stateful session bean retains the conversational state of the client across multiple method calls. Stateless session beans are dedicated to a client only for the duration of a single method call. Session beans do not survive crashes of the EJB container. Entity beans provide object representation of data in the database. They can allow shared access from multiple users. The entity, its primary key, and remote reference can survive the crash of the EJB container. Message-driven beans (MDBs) are asynchronously invoked when a client message arrives. Clients never call them directly, so they do not have any home or component interfaces.

EJB 2.0

Page 4 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Guaranteed features EJB 2.0 technology has simplified the development and deployment of J2EE applications to a great extent. EJB 2.0 provides the following important features: ° Integration with Java Messaging Service (JMS) MDBs can receive and respond to JMS messages without the need for an application client user interface. ° Container-managed persistence (CMP) for entity beans Container generates the database access code, thus resulting in portable applications. ° Local component and home interfaces for session and entity beans Provides a local client view and support for efficient, lightweight access to enterprise beans from local clients. ° Home business methods for entity beans Allows you to define business methods in the home interface of entity beans. ° EJB Query Language (EJB-QL) for entity bean finder and select methods Provides a portable, vendor-neutral way to define queries for finder and select methods. ° Run-as security identity functionality Allows you to specify a different principal, other than the calling client, for the execution of the bean's methods. ° Network interoperability among EJB servers Allows EJB applications deployed on servers from different vendors to interoperate using the RMI-IIOP protocol.

Supported APIs
Any EJB 2.0 container is guaranteed to provide the following APIs:

Java certification success, Part 3: SCBCD

Page 5 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° ° ° ° ° ° ° °

Java 2 Platform, Standard Edition, v1.3 (J2SE) APIs EJB 2.0 Standard Extension JDBC 2.0 Standard Extension (support for row sets only) JNDI 1.2 Standard Extension JTA 1.0.1 Standard Extension (the UserTransaction interface only) JMS 1.0.2 Standard Extension JavaMail 1.1 Standard Extension (for sending mail only) JAXP 1.0

Programming restrictions
You should avoid the following features in your EJB development to ensure you build portable EJB components: ° You must not use read/write static fields. Using read-only (final) static fields is allowed. You must not use thread synchronization primitives to synchronize execution of multiple instances. You must not attempt the use of the AWT functionality to output information to a display, or to input information from a keyboard. You must not attempt the use of the java.io package to access files and directories in the file system. You must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast. A bean may act as a network client (that is, it may make use of the java.net.Socket class), but it may not act as a network server, and thus, it must not use the java.net.ServerSocket class to accept remote connections. You must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. You must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.

°

°

°

°

°

°

°

Page 6 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

You must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams. You must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL. You must not attempt to manage threads or thread groups. You must not attempt to read or write a file descriptor directly. You must not attempt to obtain the security policy information for a particular code source. You must not attempt to load a native library. You must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean. You must not attempt to define a class in a package. You must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity). You must not attempt to use the subclass and object substitution features of the Java Serialization protocol. You must not attempt to pass the this reference of the bean as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject(), SessionContext.getEJBLocalObject(), EntityContext.getEJBObject(), or EntityContext.getEJBLocalObject() instead.

°

° ° °

° °

° °

°

°

EJB roles
The EJB specification defines six distinct roles in the application development lifecycle:

Java certification success, Part 3: SCBCD

Page 7 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° ° ° ° ° °

Enterprise Bean Provider Application Assembler Deployer EJB Container Provider EJB Server Provider System Administrator

These roles have defined sets of responsibilities, and a single party may handle more than one role: Enterprise Bean Provider Designs and develops the EJB components. The Bean Provider codes the Java classes that implement the enterprise bean's business methods, the bean's home, and component interfaces. The deliverables are ejb-jar files (that include one or more beans and an XML deployment descriptor). Application Assembler Combines multiple enterprise beans with other types of application components (for instance, JSP components) to compose an application. The Application Assembler delivers one or more ejb-jar files that contain the enterprise beans along with their application assembly instructions. Deployer Takes one or more ejb-jar files produced by a Bean Provider or Application Assembler and deploys them in a specific EJB container. The Deployer delivers enterprise beans that have been customized for the target operational environment. To perform their role, the Deployers use tools provided by the EJB container. EJB Container Provider Gives runtime support for the deployed enterprise bean instances. The Container Provider also delivers the deployment tools necessary for the deployment of enterprise beans and tools that allow the System Administrator to monitor and manage the container and the beans. EJB Server Provider A specialist in the area of distributed objects, transactions, and other lower-level system-level services. A typical EJB Server Provider is an OS vendor, middleware vendor, or database vendor. The current EJB architecture assumes that the EJB Server Provider and the EJB Container Provider roles are the same vendor. System Administrator
Page 8 of 115 Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Responsible for the configuration and administration of the enterprise's computing and networking infrastructure that includes the EJB server and container. It also oversees the well being of the deployed enterprise bean applications at runtime.

Requirements for an ejb-jar file
The ejb-jar file is the standard format for the packaging of enterprise beans. The ejb-jar file must contain, either by inclusion or by reference, the class files of each enterprise bean as follows: ° ° ° The enterprise bean class The enterprise bean home and component interfaces (not for MDBs) The primary key class, if the bean is an entity bean

The ejb-jar file must contain the deployment descriptor, stored with the name ejb-jar.xml in the META-INF folder. The ejb-jar file must also contain, either by inclusion or by reference, the class files for all the classes and interfaces that each enterprise bean class and the home and component interfaces depend upon, except J2EE and J2SE classes. The ejb-jar file is not required to contain the manifest file. The stubs for remote interfaces and classes implementing the component, home interfaces are generated by the container and hence are not included in the ejb-jar file.

Sample questions
Question 1: Which of the following must not be packaged in the ejb-jar file of an entity bean? Choices: ° ° ° ° ° A. The primary key class of the bean B. Classes used as method return types C. Exception classes D. Stub of the EJB Object E. Classes used as method arguments

Java certification success, Part 3: SCBCD

Page 9 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Correct choice: D Explanation: The ejb-jar file is the standard format for packaging enterprise beans and assembled applications. It contains the XML deployment descriptor, the enterprise bean classes, the enterprise bean remote and home interfaces, and the primary key class (only for entity beans). The ejb-jar should also contain the superclasses and superinterfaces of the above classes. It should also include the dependent classes and the classes and interfaces used as method parameters, return types, and exceptions. So choices A, B, C, and E are incorrect. To learn more about the ejb-jar file, refer to section 23 of the EJB 2.0 specification (see Resources on page113 ). Question 2: Which of the following are not allowed in enterprise beans according to the EJB 2.0 programming restrictions? Choices: ° ° ° ° ° A. Extending from a class B. Creating client sockets C. Having read/write static fields D. Loading native libraries E. Managing threads

Correct choice: C, D, and E Explanation: The Bean Provider must follow some programming restrictions to ensure that the enterprise bean is portable and can be deployed in all EJB 2.0 containers. An enterprise bean must not use read/write static fields, however static fields are allowed if they are made read-only by declaring them with the final keyword. The bean must not attempt to load a native library; this restriction is to avoid security holes. The enterprise bean must not manage threads or thread groups because these functions are reserved for the EJB container. Choice A is incorrect because Java inheritance is allowed for enterprise bean

Page 10 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

classes. Choice B is incorrect because the EJB architecture allows an enterprise bean instance to be a network client. However, it does not allow it to be a network server. For a complete list of the EJB 2.0 programming restrictions, please refer to section 24.1.2 of the EJB 2.0 specification (see Resources on page113 ).

Summary
This section provided an overview of the EJB architecture and the different types of enterprise beans. We discussed which features and APIs are guaranteed to be supported by the EJB 2.0 specification, and you now know the programming restrictions on EJB business methods to ensure that the bean is portable and can be deployed in any compliant EJB 2.0 container. The responsibilities of the different roles involved in the EJB development lifecycle are spread over the remaining objectives. In this objective, we have simply provided an overall picture of the responsibilities of each role.

Java certification success, Part 3: SCBCD

Page 11 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 3. Client view of a session bean Local and remote clients
A session bean can use its component interface to expose its business methods to clients. The Java object that implements the component interface is called the EJB Object of the bean. To invoke a business method on a session bean, the client needs to get a reference to the bean's EJB Object. The client obtains a reference to the EJB Object by calling a method on the home object of the bean. The home object is a Java object that implements the home interface of the bean. A local client of a session bean is collocated in the same JVM as the bean. Here, the local component and home interfaces provide the client view. The local client view is not location-independent. The arguments and results of the methods of the local interface and local home interface are passed by reference. A remote client of a session bean can be another enterprise bean deployed in the same or different container; or it can be an arbitrary Java program, such as an application, applet, or servlet. It can even be a non-Java program, such as a CORBA client. Here the remote component and home interfaces provide the client view. The remote client view of a session bean is location-independent. The arguments and results of the methods of the remote interface and remote home interface are passed by value. Even though it is possible for a session bean to have a local view and a remote view, typically a session bean provides only one of these.

Locating the home object
A client locates the home object of a session bean using the Java Naming and Directory Interface (JNDI). The InitialContext class is the starting context for performing JNDI naming operations. The lookup method takes the bean's JNDI name as the argument:
Context initialContext = new InitialContext();

CartHome cartHome = (CartHome)javax.rmi.PortableRemoteObject.narrow(initialContext.lookup("ejb/cart"),

Page 12 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

CartHome.class);

When looking up the remote home object, the PortableRemoteObject.narrow() method must be used on the object returned from the JNDI lookup, rather than using simple Java language casts. This method is required because the remote home stub, which is obtained from the JNDI lookup, is RMI-IIOP compatible and needs to be converted into a Java object that actually implements the home interface. In the case of local clients, the return value of the InitialContext.lookup() method can be directly cast to the local home interface because the object returned is not a stub:
Context initialContext = new InitialContext(); CartHome cartHome = (CartHome)initialContext.lookup("java:comp/env/ejb/cart");

Remote home interface
The remote home interface of an EJB extends the javax.ejb.EJBHome interface. The remote home interface allows a client to: ° ° ° ° Create a new session object Remove a session object Get the EJBMetaData interface for the session bean Obtain a handle for the remote home interface

Creating a new session object The home interface of a stateful session bean defines one or more create<METHOD>(...) methods to create a session object. The return type of a create<METHOD>(...) method is the session bean's remote component interface:
public interface CustomerHome extends javax.ejb.EJBHome { Customer create(String name, String accountNo) throws RemoteException, BadAccountException, CreateException; Customer createPrivilegedCustomer(String name, String accountNo, int privilege)

Java certification success, Part 3: SCBCD

Page 13 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

throws RemoteException, CreateException; }

The home interface of a stateless session bean defines only one create method, which does not take any arguments. Removing a session object The EJBHome interface defines two remove() methods: ° ° void remove(Handle handle) void remove(java.lang.Object primaryKey)

A session bean can be removed by invoking the first remove() method, passing the Handle as the argument. As session beans do not have primary keys, invoking the remove(Object primaryKey) method results in javax.ejb.RemoveException. For example:
MyRemote bean1=myHome.create(); Handle handle=bean1.getHandle(); // Call the bean business methods here. myHome.remove(handle);

Getting the EJBMetaData The EJBMetaData interface allows the client to obtain class information about the enterprise bean. This information is usually required by tools. The getEJBMetaData() method of the EJBHome interface returns an object that implements this interface:
public EJBMetaData getEJBMetaData()

Obtaining a home handle The home handle is a serializable object that can be used at a later time to re-obtain a reference to the remote home object, possibly in a different JVM. The getHomeHandle() method of EJBHome can be called to obtain the following:
public HomeHandle getHomeHandle()

Page 14 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Local home interface
The local home interface extends the javax.ejb.EJBLocalHome interface and allows a client to create a new session object. A local client can create a session object by invoking any one of the create<METHOD> (...) methods, defined in the local home interface. The only method defined in EJBLocalHome is void remove(java.lang.Object primaryKey). This method cannot be invoked by a client because session beans do not have primary keys. As a consequence, local clients cannot remove a session bean by calling any methods on the home interface of the session bean. Local clients do not need an EJBMetaData interface because they can use reflection to extract bean information. Also, handles are not required for local clients because there aren't any stubs.

Component interface
The component interface exposes the business methods of the session object to clients. The EJB Object, which implements this interface, delegates invocation of a business method to the session bean instance. The remote component interface extends the javax.ejb.EJBObject interface. The methods inherited from the EJBObject interface are: ° ° ° ° ° EJBHome getEJBHome() Handle getHandle() java.lang.Object getPrimaryKey() boolean isIdentical(EJBObject obj) void remove()

The local component interface extends the javax.ejb.EJBLocalObject interface. The methods inherited from the javax.ejb.EJBLocalObject interface are: ° ° ° EJBLocalHome getEJBLocalHome() java.lang.Object getPrimaryKey() boolean isIdentical(EJBLocalObject obj)

Java certification success, Part 3: SCBCD

Page 15 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

°

void remove()

Invoking the getPrimaryKey() method for a session object raises a RemoteException in the case of an EJBObject and an EJBException for the EJBLocalObject interface. Getting the home object reference If the reference to the EJB Object is available, we can get a reference to the bean's home object using the getEJBHome() method for remote clients and getEJBLocalHome() for local clients. This method of obtaining the home object reference is more efficient than performing a JNDI lookup to locate the home. Getting the handle A handle is a serializable object that abstracts a network reference to an EJB Object. The Handle interface is implemented by all the EJB object handles. The client can serialize the Handle object at any time and deserialize it later to obtain a reference to the original EJB object. The EJBObject.getHandle() method returns a Handle object. Because local clients do not need handles, the EJBLocalObject interface does not define a similar method. Removing the bean The remove method in the EJBObject and EJBLocalObject interfaces can be used to remove the EJB Object. It tells the container to free up any resources held for the bean. Comparing session objects The isIdentical() method defined in EJBObject and EJBLocalObject is used to compare two EJB Object references. Stateless session beans created from the same home have the same identity assigned by the container. For example:
MyStatelessBean myStatelessBean1 = myStatelessBeanHome.create(); MyStatelessBean myStatelessBean2 = myStatelessBeanHome.create(); if (myStatelessBean1.isIdentical(myStatelessBean1)) { // this test returns true } if (myStatelessBean1.isIdentical(myStatelessBean2)) { // this test returns true }

When creating a stateful session bean, the EJB container assigns it a unique identity because they hold the client conversational state. So two stateful

Page 16 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

session bean instances created from the same home are not considered identical. For example:
MyStatefulBean myStatefulBean1 = myStatefulBeanHome.create(...); MyStatefulBean myStatefulBean2 = myStatefulBeanHome.create(...); if (myStatefulBean1.isIdentical(myStatefulBean1)) { // this test must return true } if (myStatefulBean1.isIdentical(myStatefulBean2)) { // this test must return false }

Sample questions
Question 1 What do remote and local component interfaces of session beans have in common? Choices: They provide support for: ° ° ° ° ° A. Creating new session beans B. Removing the session bean C. Retrieving their respective home interfaces D. Getting a handle to the component interface E. Getting the primary key of the associated session beans

Correct choice: B and C Explanation: Choice A is incorrect because creating new session beans is clearly the responsibility of the (remote or local) home interface. Choice B is correct because the component interface provides a method called remove() that allows the client to remove the associated session bean. Choice C is correct because the local and remote component interfaces provide methods called getEJBLocalHome() and getEJBHome() that return the local and remote home interfaces of the session bean, respectively.
Java certification success, Part 3: SCBCD Page 17 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Choice D is incorrect because only the remote component interface provides the ability to get a handle for later use. Choice E is incorrect because session beans do not make their identity available to clients. As a result, when the getPrimaryKey() method is invoked on the local and remote component interfaces, a javax.ejb.EJBException and java.rmi.RemoteException will be thrown respectively to the client. Please refer to section 6.5 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: What kind of argument must be passed to the isIdentical() method to test whether two remote component interface references are referring to the same session bean? Choices: ° ° ° ° ° A. An object of type java.lang.Object B. An object of type javax.ejb.EJBObject C. An object of type javax.ejb.EJBLocalObject D. An object of type javax.ejb.SessionBean E. An object of type javax.ejb.SessionContext

Correct choice: B Explanation: The isIdentical() method is defined in two different interfaces -javax.ejb.EJBObject and javax.ejb.EJBLocalObject. Because we want to test remote component interfaces, we consider the former one, which defines the isIdentical() method as follows:
public boolean isIdentical(EJBObject other);

Please refer to section 6.9 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
Page 18 of 115 Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

This section focused on the client view of the remote and local interfaces of session beans. First, you learned how to perform a JNDI lookup to locate the home object of a bean. It is important to note the differences in code for when the home is remote and when the home is local. You also observed the details of the methods in the home and component interfaces -- both local and remote.

Java certification success, Part 3: SCBCD

Page 19 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 4. Session bean component contract Overview of session beans
Session beans are responsible for managing client processes. They are relatively short-lived and do not survive server crashes. Though they do not represent shared data in the database, they may access or update such data. Stateful session beans retain the conversational state of the client, while Stateless session beans are dedicated to a client only for the duration of the method call. Stateless session beans can have instance variables, but they cannot preserve client data across multiple method invocations. All instances of a particular type of stateless session bean are equivalent, so the container may choose any available instance to serve a client method call. Two successive client calls to a stateless session bean may be served by two different instances of that session bean. All session beans must implement the javax.ejb.SessionBean interface. The container uses the SessionBean() methods to notify lifecycle events to the enterprise bean instances. The methods defined in this interface are: ° ° ° ° void void void void ejbActivate() ejbPassivate() ejbRemove() setSessionContext(SessionContext ctx)

The setSessionContext() method is invoked on a session bean instance after its construction. The SessionContext reference may be stored in an instance field of the session bean for future use. The ejbPassivate() notification signals the intent of the container to passivate the instance. The ejbActivate() notification signals that the instance has just been reactivated. The ejbRemove() notification signals that the instance is in the process of being removed by the container. The ejbPassivate() and ejbActivate() methods are invoked only in the life of stateful beans and not for stateless session beans. The reason is that stateless session beans do not need to persist the client state. All the instances of a particular type of a stateless session bean are equivalent, and the same instance may be reused to serve multiple clients. Even though stateless beans

Page 20 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

are never passivated, we need to define the ejbActivate() and ejbPassivate() callback methods in the bean class because the class implements the SessionBean interface. For example:
public class HelloBean implements SessionBean { private SessionContext sessionContext; public void ejbCreate() { } public void ejbRemove() { } public void ejbActivate() { } public void ejbPassivate() { } public void setSessionContext(SessionContext sessionContext) { this.sessionContext = sessionContext; } public String sayHello() { return "Hello World!!!!!"; } }

A client creates a session bean instance using one of the create <METHOD>() methods defined in the session bean's home interface. The container calls the ejbCreate<METHOD>() method whose signature matches that of the create <METHOD>() method. Each stateful session bean class must have at least one ejbCreate<METHOD>() method. The stateless session bean class can have only one ejbCreate() method, which must not take any arguments.
// Home interface public interface HelloHome extends EJBHome { public HelloObject create() throws RemoteException, CreateException; }

// Remote interface public interface HelloObject extends EJBObject { public String sayHello() throws RemoteException; }

Passivation of a stateful session bean
A stateful session bean may be inactive between client calls. To conserve resources, the container may disassociate the bean from the EJBObject, saving its state to a secondary storage. This process is called passivation. Restoring the bean from the passivated state is called activation.

Java certification success, Part 3: SCBCD

Page 21 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Responsibilities of the bean provider All open resources, such as JDBC connections, must be closed in the ejbPassivate() method and reopened in ejbActivate(). After ejbPassivate(), the non-transient fields of the bean may consist of only primitive values, serializable objects, null, and the following special types: ° ° ° ° ° ° ° ° ° An enterprise bean's remote interface reference An enterprise bean's remote home interface reference An entity bean's local interface reference An entity bean's local home interface reference A reference to the SessionContext object A reference to the environment naming context (java:comp/env JNDI context) A reference to the UserTransaction interface A reference to a resource manager connection factory An object that is not directly serializable, but becomes serializable by replacing the references to the special types mentioned above with serializable objects

The Bean Provider should not store in a transient field a reference to any of the following objects: ° ° ° ° SessionContext object Environment JNDI naming context and any of its subcontexts Home and component interfaces UserTransaction interface

The content of transient fields may be lost between the ejbPassivate and ejbActivate notifications. Responsibilities of the container The container performs Java serialization (or its equivalent) to passivate the bean instance. A stateful session bean may not be passivated while it is participating in a transaction. The container must be able to properly save and restore the special types mentioned in the previous section, even though they are not serializable. A session bean instance may be destroyed if the instance does not meet the passivation requirements.

SessionContext interface

Page 22 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

The SessionContext interface represents the bean's context maintained by the container. A reference to the SessionContext object is passed to the bean when the container invokes the setSessionContext() callback method. The methods defined in this interface are as follows: ° ° ° ° ° getEJBObject(): Returns the session bean's remote interface. getEJBHome(): Returns the session bean's remote home interface. getEJBLocalObject(): Returns the session bean's local interface. getEJBLocalHome(): Returns the session bean's local home interface. getCallerPrincipal(): Returns the java.security.Principal that identifies the invoker of the bean instance's EJB Object. isCallerInRole(): Tests whether the session bean instance's caller has a particular role. setRollbackOnly(): Allows the instance to mark the current transaction for a rollback. It is only for session beans with container-managed transaction (CMT) demarcation. getRollbackOnly(): Allows the instance to test whether the current transaction has been marked for roll back. It is only for session beans with CMT demarcation. getUserTransaction(): Returns a javax.transaction.UserTransaction reference for use by session beans with bean-managed transaction (BMT) demarcation.

°

°

°

°

SessionSynchronization interface
A stateful session bean with CMT demarcation may implement the javax.ejb.SessionSynchronization interface to receive notifications when a transaction starts, when it is about to end, and when it is over. These notifications are helpful for the bean to perform database synchronization operations.

Java certification success, Part 3: SCBCD

Page 23 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

The javax.ejb.SessionSynchronization interface declares the following methods: ° afterBegin(): Notifies the bean instance that a new transaction has started. beforeCompletion(): Notifies the instance that a transaction is about to be committed. This method is not invoked if the transaction is marked for rollback. afterCompletion(boolean flag): Notifies the instance that the current transaction has completed. The flag is true if the transaction has been committed and false if it has been rolled back.

°

°

BMT beans must not implement this interface, because they are themselves responsible for demarcating transactions. Stateless session beans are not allowed to maintain transactions across multiple methods, so they must not implement this interface.

Responsibilities of the Bean Provider
The Bean Provider is responsible for delivering the following files: ° ° Session bean class Session bean's remote interface and remote home interface, if the session bean provides a remote client view Session bean's local interface and local home interface, if the session bean provides a local client view

°

The classes must follow certain programming guidelines as specified below. Session bean class ° It must implement the javax.ejb.SessionBean interface. ° ° ° It must be defined as publi, must not be final or abstract. It must have a public constructor that takes no parameters. It must not define the finalize() method.

Page 24 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

It may (but is not required to) implement the session bean's component interface. It must implement the business methods and the ejbCreate() methods. If the class is a stateful session bean, it may optionally implement javax.ejb.SessionSynchronization. The session bean class may have superclasses and/or superinterfaces.

° °

°

ejbCreate<METHOD>() methods ° The session bean class must define one or more ejbCreate<METHOD>(...) methods in the case of stateful session beans, and no more than one no-argument ejbCreate() method in the case of stateless session beans. ° ° ° ° The method name must have ejbCreate() as its prefix. It must be declared as public, but not final or static. The method return type must be void. The method arguments must be legal types for RMI/IIOP if there is a create<METHOD>(...) method corresponding to the ejbCreate(...) method on the session bean's remote home interface. The throws clause of the method may define arbitrary application exceptions, including javax.ejb.CreateException.

°

Business methods ° The method names can be arbitrary, but they must not start with "ejb". ° ° ° The business method must be declared as public. The method must not be declared as final or static. The argument and return value types for a method must be legal types for RMI/IIOP if the method corresponds to a business method on the session bean's remote interface.

Java certification success, Part 3: SCBCD

Page 25 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

°

The throws clause may define arbitrary application exceptions, but they must not declare java.rmi.RemoteException.

Component interface ° The remote interface must extend the EJBObject interface and the local interface must extend the EJBLocalObject interface. ° The methods defined in the remote interface must follow the rules for RMI/IIOP. The interface is allowed to have superinterfaces. For each method defined in the interface, there must be a matching method in the session bean's class. All the exceptions defined in the throws clause of the matching method of the session bean class must be defined in the throws clause of the method of the interface. The remote interface methods must not expose local home or component interface types. The remote interface methods must define java.rmi.RemoteException in the throws clause, while the local interface methods must not.

° °

°

°

°

Home interface ° The remote home interface must extend the EJBHome interface and the local home interface must extend the EJBLocalHome interface. ° ° The home interface is allowed to have superinterfaces. The home interface must define one or more create<METHOD>(...) methods. A stateless session bean must define exactly one create() method with no arguments. Each create() method must be named create<METHOD>, and it must match one of the ejbCreate<METHOD> methods defined in the session bean class, the return type is different. The methods for a stateless session bean must be named create() and

°

°

Page 26 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

ejbCreate(). ° The return type for a create<METHOD>() method must be the session bean's component interface type. The remote home interface methods must define java.rmi.RemoteException in the throws clause, while the local home interface methods must not. The throws clause of the create() methods must include javax.ejb.CreateException.

°

°

Responsibilities of the container
The deployment tools provided by the container are responsible for the generation of the following classes: ° ° ° ° ° ° A class that implements the session bean's remote home interface A class that implements the session bean's remote interface A class that implements the session bean's local home interface A class that implements the session bean's local interface The handle classes for the session bean's remote home and remote interfaces A class that implements the EJBMetaData interface and provides metadata to the remote client view contract.

The container must ensure that only one thread is executing an instance at any time. If a client request arrives for an instance while the instance is executing another request, the container may throw java.rmi.RemoteException to the second request if the client is a remote client, or javax.ejb.EJBException if the client is a local client.

Sample questions
Question 1: Which of the following method declarations for a session bean class are valid?

Java certification success, Part 3: SCBCD

Page 27 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Choices: ° ° ° ° ° ° A. public void ejbCreate(String name) throws CreateException {} B. public void ejbCreateBigCart() throws CreateException {} C. public void ejbCreate(String name) {} D. public static void ejbCreateSmallCart() {} E. public final PKeyType ejbCreate() {} F. public PKeyType ejbCreateLargeAccount() {}

Correct choice: A and B Explanation: A session bean class must declare one or more ejbCreate() methods that must be prefixed with ejbCreate. Moreover, the method declaration must be public, it must neither contain the final nor static modifiers, its arguments must be legal RMI-IIOP types, the return type must be void (session beans hide their identity, which is the main difference between them and entity beans!), and its throws clause must contain the javax.ejb.CreateException as well as arbitrary application exceptions. Thus, only choices A and B are correct. Moreover, each ejbCreate<METHOD>() method must correspond to a create()<METHOD> method in the session bean's remote or local home interface. Note that in the case of stateless session beans, the rules are more restrictive. There must be exactly one method, it must be called ejbCreate, and it must not take any arguments. The other rules mentioned above still apply. Please refer to section 7.10.3 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: Which of the following are defined by the javax.ejb.SessionBean interface? Choices: ° ° ° A. A setSessionContext() method that takes an argument of the type javax.ejb.EJBContext B. An unsetSessionContext() method C. Three methods that have the same signature as methods defined in the

Page 28 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

° °

javax.ejb.EntityBean interface D. The ejbActivate() method E. Methods to create new session beans

Correct choice: C and D Explanation: Choice A is incorrect because, while the javax.ejb.SessionBean interface does define a setSessionContext() method, the argument is of type javax.ejb.SessionContext and not javax.ejb.EJBContext. Choice B is incorrect because the javax.ejb.SessionBean interface does not declare any method called unsetSessionContext(). It is worth noting that only the javax.ejb.EntityBean interface defines a method for unsetting the context of the bean. Choice C is correct because both the javax.ejb.SessionBean and the javax.ejb.EntityBean interfaces define three methods that have the same signature: ° ° ° public void ejbActivate() public void ejbPassivate() public void ejbRemove()

Note that the return type and the throws clause are not part of the signature of a method. From the above explanation, it follows that choice D is also correct. Choice E is incorrect because the ability to create new session beans is provided through the local or remote home interface. Please refer to section 7.5.1 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
Thi section briefly covered the differences between stateful and stateless session beans. We identified the methods defined in the SessionBean and SessionContext interfaces. The significance of the

Java certification success, Part 3: SCBCD

Page 29 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

SessionSynchronization interface, which can be optionally implemented by stateful session beans, was also discussed. Finally, we concentrated on the responsibilities of the Bean Provider and the container with regard to session beans.

Page 30 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 5. Session bean lifecycle Stateful session beans
The lifetime of a stateful session bean instance is controlled by the client. The bean contains conversational state that must be retained across methods and transactions. The following figure illustrates the lifecycle of a stateful session bean instance:

At first, the bean is in the Does-not-exist state. The client invokes the create() method on the home of the bean. The container instantiates the bean and invokes the setSessionContext() method, passing a SessionContext instance. The bean is assigned to its EJB Object. The container invokes the ejbCreate() method matching the create() method invoked by the client. The reference to the EJB Object is returned to the client; now the bean is in the Ready state. The container might choose to passivate an inactive bean instance to conserve resources. When the bean is about to be passivated, the ejbPassivate() method is invoked. A session bean cannot be passivated while it is in a transaction. If a client invokes a session object whose session bean instance has been passivated, the container will activate the instance. To this end, the container invokes ejbActivate() on the bean after successfully restoring it from the Passive state. If the client invokes the remove() method on the bean, the container invokes ejbRemove() on the bean and moves out of the Ready state into the Does-not-exist state. This can also happen when a bean times out in the Ready state. Note that the bean cannot time out while in a transaction.

Java certification success, Part 3: SCBCD

Page 31 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Under certain conditions, the ejbRemove() method might not be invoked on a session bean instance, such as: ° ° ° If the container crashes If a bean method throws a system exception If the bean times out while in the Passive state

Stateless session beans
As you can see in the figure below, the lifecycle of a stateless session bean is much simpler as compared to that of a stateful session bean. The container can instantiate the stateless session bean at any time, it is not related to the client's invocation of the create() method. The stateless session bean is not passivated or activated, because it does not maintain any client state.

After instantiation, the container invokes setSessionContext() followed by ejbCreate(), and the bean is ready to serve client requests. When a client invokes the create() method on the home interface of a stateless session bean, an EJB Object is created for the bean and returned to the client. The container selects one of its method-ready instances and ties it to the client's EJB Object, only when the client calls a business method. After serving the client, the bean is disassociated from the EJB Object and returns to the Ready state. When the container no longer needs the instance, the container invokes ejbRemove() on it.

Page 32 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Operations allowed in the methods of a stateful session bean
° getEJBObject() and getEJBLocalObject() of SessionContext Can be invoked from all the methods except setSessionContext() and the constructor because there is no session object identity available in those methods. ° getCallerPrincipal() and isCallerInRole() of SessionContext Can be invoked from all the methods except setSessionContext() and the constructor because there is no client security context available in those methods. ° getRollbackOnly() and setRollbackOnly() of SessionContext Can be invoked only from the afterBegin() and beforeCompletion() business methods because there is no meaningful transaction context available in other methods. Moreover, only beans with CMT demarcation can invoke these methods. ° getUserTransaction() of SessionContext methods of UserTransaction Can be invoked from the ejbCreate(), ejbRemove(), ejbActivate(), and ejbPassivate() business methods of beans with BMT demarcation. ° Accessing resource managers and enterprise beans Not allowed in the session bean methods for which the container does not have a meaningful transaction context or client security context. So they can be called in every method except setSessionContext() and afterCompletion(). ° getEJBHome() and getEJBLocalHome() of SessionContext, JNDI access to java:comp/env Allowed in all methods except the constructor.

Operations allowed in the methods of a stateless session bean
Java certification success, Part 3: SCBCD Page 33 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

°

getEJBObject() and getEJBLocalObject() of SessionContext Can be invoked from all the methods except setSessionContext() and the constructor because there is no session object identity available in those methods.

°

getCallerPrincipal() and isCallerInRole() of SessionContext Can be invoked from business methods only because there is no client security context available in other methods.

°

getRollbackOnly() and setRollbackOnly() of SessionContext Can be invoked only from business methods because there is no meaningful transaction context available in other methods. Only beans with CMT demarcation can invoke these methods.

°

getUserTransaction() of SessionContext Can be invoked from the ejbCreate() and ejbRemove() business methods of beans with BMT demarcation.

°

Methods of UserTransaction Can be invoked only from business methods of beans with BMT demarcation.

°

Accessing resource managers and enterprise beans Not allowed in the session bean methods for which the container does not have a meaningful transaction context or client security context. So they can be called only from business methods.

°

getEJBHome() and getEJBLocalHome() of SessionContext, JNDI access to java:comp/env Allowed in all the methods except the constructor.

Sample questions
Question 1: Which of the following events will result in a stateful session bean transiting to the Does-not-exist state?

Page 34 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Choices: ° ° ° ° ° A. The bean times out while in the method-ready or passive state. B. The EJB container passivates the bean. C. The client invokes ejbRemove() on the bean instance. D. The client tries to invoke a method for which it does not have sufficient security credentials. E. The client invokes remove() on the component interface of the bean.

Correct choice: A, D, and E Explanation: Three ways exist for making a stateful session beans transit to the Does-not-exist state. When either the bean is in the Ready state and a timeout occurs (choice A) or the client invokes remove() on the component interface of the bean (choice E), the EJB container invokes ejbRemove() on the bean instance, which makes it transit to the Does-not-exist state. Choice B is incorrect because when the EJB container passivates the bean instance -- that is, it invokes the ejbPassivate() method on it -- the bean goes from the method-ready state to the Passive state. Choice C is incorrect because it is the container's job to invoke ejbRemove() on the bean instance. The client doesn't have access to this method. Choice D is correct because if a client invokes a method for which the access has been denied by the EJB container, the EJB container throws a java.rmi.RemoteException to a remote client and a javax.ejb.EJBException to a local client. These are considered to be system exceptions. When a system exception is thrown from any method of the bean regardless of its current state, the bean goes to the Does-not-exist state. Please refer to sections 7.6 and 21.6.9 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: Which of the following operations are allowed in the afterCompletion() method of a session bean that defines a remote client view? Choices: ° A. Invoke getPrimaryKey() on the SessionContext object

Java certification success, Part 3: SCBCD

Page 35 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° ° ° °

B. Access another enterprise bean C. Invoke getEJBLocalHome() on the SessionContext object D. Invoke getEJBObject() on the SessionContext object E. Access the java:comp/env JNDI context

Correct choice: D and E Explanation: Based on the question, it is clear that we are dealing with a stateful session bean with a CMT demarcation because it defines the afterCompletion() method of the javax.ejb.SessionSynchronization interface. BMT session beans and stateless session beans are not allowed to implement that interface. Choice A is incorrect because session beans do not publicly release their primary key, which is kept internal to the container. Choice B is incorrect because a session bean must not access another enterprise bean while executing the afterCompletion() callback. Choice C is incorrect because the question states that the session bean defines a remote client view. As a result, it is not allowed to invoke getEJBLocalHome() on the SessionContext object. An IllegalStateException is thrown by the container if it does. Choice D is correct because it is perfectly acceptable for the session bean to invoke the getEJBObject() method on the SessionContext object. Choice E is correct because the bean is allowed to perform JNDI lookups from any instance method of the session bean class, except from constructors. Please refer to section 7.6.1 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
This section addressed the details of stateless and stateful session bean lifecycles. You must be able to arrange the various lifecycle events in the proper order. Because stateless session beans do not maintain client state, their lifetime is not controlled by the client, which makes the event flow different from

Page 36 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

that of stateful beans. We also reviewed the operations that are allowed to be performed from the various bean methods.

Java certification success, Part 3: SCBCD

Page 37 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 6. Client view of an entity Overview
Entity beans allow their clients to access and manipulate data from a database in an object-oriented manner. Multiple clients may access an entity object concurrently. It is the responsibility of the container to synchronize the access by means of transactions. An entity bean may provide a remote client view, a local client view, or both. While the remote client view is location dependent, the local client view is not. However, to be the target of container-managed relationships (CMRs), entity beans need to provide local interfaces. While a crash of the JVM may result in a rollback of current transactions, it does not destroy previously created entity objects nor does it invalidate the references to the home and component interfaces held by clients.

Home interface
The home interface allows the client to create, find, and remove entity objects within the enterprise bean's home as well as to execute home business methods, which are not specific to a particular entity bean. For each entity bean deployed in a container, the container provides a class that implements a home interface for the entity bean. The following code illustrates the definition of the remote home interface of an entity bean.
public interface EmployeeHome extends EJBHome { public Employee create () throws RemoteException, CreateException; public Employee findByPrimaryKey(String name) throws RemoteException, FinderException; public Employee createWithDetails (Integer SSN, String name) throws RemoteException, CreateException; }

The remote home interface extends the javax.ejb.EJBHome interface. Methods provided by EJBHome are as follows: ° ° EJBMetaData getEJBMetaData() HomeHandle getHomeHandle()

Page 38 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

° °

void remove(Handle handle) void remove(java.lang.Object primaryKey)

The local home interface of an entity bean extends the javax.ejb.EJBLocalHome interface. The local home methods must not throw RemoteException. The method provided by EJBLocalHome is void remove(java.lang.Object primaryKey). Creating entity objects The create methods are used for creating new entities, which results in insertion of new rows in the database. For entity beans, create methods are optional in the home interface. Typically, they take arguments, though it's not mandatory. In addition: ° ° ° ° ° There can be zero or more create methods. They must start with the prefix create. They have to match the ejbCreate() and ejbPostCreate() methods on the bean class. Their return type is the component interface of the bean. The throws clause must include javax.ejb.CreateException. In addition, java.rmi.RemoteException must be included if the home interface is remote. The throws clause may include additional application-level exceptions.

°

The following code illustrates a client looking up a home object reference and invoking one of the create methods:
Context initialContext = new InitialContext(); EmployeeHome empHome = (EmployeeHome)javax.rmi.PortableRemoteObject.narrow( initialContext.lookup("java:comp/env/ejb/emp"), EmployeeHome.class); EmployeeRemote emp = empHome.createWithDetails(new Integer(3),"John"));

Finding entity objects An entity bean client needs to work with existing data more frequently than creating new entities. Multiple finder methods can be defined in the home interface for the purpose of obtaining references to existing entities. In addition: ° There can be one or more finder methods.

Java certification success, Part 3: SCBCD

Page 39 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° °

The method name must start with the prefix find. The throws clause contains javax.ejb.FinderException. java.rmi.RemoteException is required if the home interface is remote. The return type must be the bean's component interface or a type representing a collection of objects that implement the bean's component interface. The findByPrimaryKey() method must always be present and must have a single argument that is of the same type as the entity bean's primary key type. This method cannot be overloaded. Every finder method in the home must have a matching method in the bean class that starts with the prefix ejbFind.

°

°

°

The following code illustrates multiple finder methods defined in the remote home interface of an entity bean.
public interface AccountHome extends javax.ejb.EJBHome { public Account findByPrimaryKey(String accountNumber) throws RemoteException, FinderException; public Collection findByLastName (String lastName) throws RemoteException, FinderException; public Collection findByFirstName (String firstName) throws RemoteException, FinderException; }

After looking up the home object of the entity using JNDI, a client can invoke a finder method as shown by the code fragment below:
Account account = accountHome.findByPrimaryKey("100");

Removing entity objects The home interface provides two methods to remove entity objects. The remove() method, which takes the javax.ejb.Handle as an argument, can be called only by remote clients. The other version of the remove() method takes the primary key of the entity bean as an argument. If the method is successful, the container invokes the ejbRemove() method of the bean, removes the corresponding data from the database, and invalidates the reference to the EJB Object of the entity. For example:

Page 40 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Context initialContext = new InitialContext(); CustHome custHome = (CustHome)javax.rmi.PortableRemoteObject.narrow( initialContext.lookup("java:comp/env/ejb/cust"), CustHome.class); String pk = new String("100"); custHome.remove(pk);

Home business methods Home business methods contain business logic that is not specific to an entity bean instance. They are ideal for batch operations. In addition: ° ° Their names must not start with "create," "find," or "remove." If the home is remote, the throws clause must include the java.rmi.RemoteException. Also, the arguments and return types must be RMI-IIOP compatible. They may also include additional application-level exceptions. They must have a corresponding ejbHome() method in the bean class.

° °

The following example shows a home business method declaration:
public interface EmployeeHome extends javax.ejb.EJBHome { Collection getAllEmployeeNames(String state) throws RemoteException; // other methods here }

Component interface
A client can access an entity object through the entity bean's component interface, which defines the business methods callable by clients. An entity bean's remote component interface must extend the javax.ejb.EJBObject interface, and the local component interface must extend the javax.ejb.EJBLocalObject interface. These interfaces define the methods that allow the client to perform some useful operations on an entity object's reference. The implementation for these methods is provided by the container. Getting the home object reference The EJBObject interface defines getEJBHome() and the EJBLocalObject interface defines getEJBLocalHome(), which return the remote home and the local home object reference, respectively.

Java certification success, Part 3: SCBCD

Page 41 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Getting the entity bean handle An entity object's handle is a serializable object that identifies the entity object on a network. A remote client can obtain the entity object's handle by invoking the getHandle() method on the remote component interface. The getHandle() method is only available on the remote component interface and not on the local one. Getting the primary key of the entity Every entity object has a unique identity within its home, which is denoted by its primary key. A client can determine the entity object's identity within its home by invoking the getPrimaryKey() method on the component interface. If an entity object has both a remote home interface and a local home interface, the result of invoking the getPrimaryKey() method on a reference to the entity object's remote interface and on a reference to the entity object's local interface is the same. Comparing entity objects A client can test whether two entity object references refer to the same entity object by using the isIdentical() method. Alternatively, if a client obtains two entity object references from the same home, it can determine if they refer to the same entity by comparing their primary keys using the equals() method: ° ° boolean isIdentical(EJBObject obj): To be called by remote clients boolean isIdentical(EJBLocalObject obj): To be called by local clients

Removing entity objects The remove() method provided by the EJBObject and EJBLocalObject interfaces can be used to remove entity objects.

Sample questions
Question 1: Which of the following statements about the EJBLocalObject interface of an entity bean are true? Choices: ° A. It does not define a getHandle() method.

Page 42 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

° ° ° °

B. It does not define a getPrimaryKey() method. C. It does not define the isIdentical() method. D. Its methods do not throw RemoteException. E. Its methods do not throw EJBException.

Correct choice: A and D Explanation: A local client can access an enterprise bean using the bean's local interface and local home interface. The EJBLocalObject interface does not define a getHandle() method because the client and the enterprise bean are located in the same EJB container. The Handle is a serializable reference, which allows a remote client to obtain a reference to an enterprise bean on a remote node on a network. Therefore, it is not necessary to get the Handle object in this case. The EJBLocalObject interface does define methods to get the primary key and to compare two local EJB Objects. So choices B and C are incorrect. The EJBLocalObject() methods do not throw a RemoteException because this interface is used for co-located beans in the same JVM. However, they throw EJBException when some kind of container or transaction error happens. Therefore, choice D is correct while choice E is not. For more information, refer to section 6.5 of the EJB 2.0 specification (see Resources on page113 ). Question 2: Read the following code (assume that MakeException is a valid application exception type):
public interface CarHome extends javax.ejb.EJBHome

{

public Car create(String make, String year) throws RemoteException, CreateException;

public Car create(String make) throws RemoteException, CreateException, MakeException;

public Car createRoadster(String make, String color) throws RemoteException, CreateException;

Java certification success, Part 3: SCBCD

Page 43 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

...

}

Based on the above code, select all the correct statements. Choices: ° ° A. The CarHome interface is a local home interface. B. The return type of each create() method (that is, Car) must be the type of the local component interface. C. The return type of each create() method (that is, Car) must be the type of the remote component interface. D. The create() methods are not allowed to declare application exceptions (MakeException) in their throws clause. E. The CarHome interface is allowed to declare overloaded create methods. F. This home interface could also be used as the home interface of a stateless session bean.

°

°

° °

Correct choice: C and E Explanation: Choice A is incorrect because the CarHome interface extends the javax.ejb.EJBHome interface, which denotes a remote home interface. In order for CarHome to be a local home interface, it would need to extend the javax.ejb.EJBLocalHome interface. Choice B is incorrect because CarHome is a remote home interface. Each create() method must have the return type of the remote component interface. Therefore, choice C is correct. Choice D is incorrect because nothing prevents create methods from declaring application exceptions in their throws clause. Such exceptions are thrown if some problem occurs during the bean creation process. It is perfectly admissible for home interfaces of entity beans to declare overloaded create methods. This would also be allowed for stateful session

Page 44 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

beans, but not for stateless session beans, which must declare only one create() method that is named "create" and that takes no arguments. Therefore, choice E is correct while choice F is incorrect. Please refer to sections 9.5 and 9.6 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
In this section, you learned the various ways in which clients interact with entity beans. We saw the method types exposed by the home and component interfaces and the rules for defining them. Note the significance of home business methods and how they differ from the business methods defined in the component interface. Handles are only for remote clients while primary keys can be retrieved by both remote and local clients.

Java certification success, Part 3: SCBCD

Page 45 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 7. Component contract for CMP Container-managed persistence entity beans
In a container-managed persistence (CMP) entity bean, the container generates database access code and manages synchronization of the bean state with the underlying data. This provides a separation between the entity bean class and its persistent representation, leading to data independence and bean portability. CMP also allows multiple entity beans to have CMRs among themselves. The Bean Provider uses the deployment descriptor to specify the CMP fields and CMR fields. The set of XML elements in the deployment descriptor describing the CMP and CMR fields is known as the abstract persistence schema of the entity bean. The Deployer maps the abstract persistence schema of a set of interrelated entity bean classes into the physical schema used by the underlying data store by using the container provider's tools.

CMP entity bean programming contract
Follow these guidelines when developing a CMP entity bean: ° ° ° The entity bean class must be abstract. Container-managed fields must not be defined in the bean class. The CMP and CMR fields must be specified in the deployment descriptor using the <cmp-field> and <cmr-field> elements respectively. Accessor methods must be defined in the bean class for the CMP and CMR fields. Accessor methods must be public and abstract, named with the first letter of the name of the CMP or CMR fields in uppercase, and prefixed by get or set. The accessor methods for a CMR field must be defined in terms of the local interface of the related entity bean. The Java types assigned to the CMP field are restricted to primitive types and serializable types.
Java certification success, Part 3: SCBCD

°

°

°

°

Page 46 of 115

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

The accessor methods for one-to-many or many-to-many relationships must utilize the java.util.Collection or java.util.Set interfaces. There must be no set accessor methods defined for the primary key CMP fields in the component interface of the entity bean. Accessor methods and collection classes for CMR fields must not be exposed through the remote interfaces. Local interface types must not be exposed through remote interfaces.

°

°

°

A CMP entity bean example
The following code illustrates the definition of a CMP entity bean class:
public abstract class CourseBean implements EntityBean { abstract public String getCourseId(); abstract public void setCourseId(String id); abstract public String getTrainer(); abstract public void setTrainer(String Trainer); public String ejbCreate(String course, String trainer) { setCourseId(course); setTrainer(trainer); return course; } }

Note that the CMP fields are not declared as instance variables. Instead we have defined abstract accessor methods for the container-managed fields, which map to actual database columns. The fields need to be specified in the deployment descriptor using <cmp-field> elements, as shown below:
... <entity> <ejb-name>CourseBean</ejb-name> <local-home>CourseHome</local-home> <local>Course</local> <ejb-class>example.cmp.basic.CourseBean</ejb-class> <prim-key-class>String</prim-key-class> <primkey-field>courseId</primkey-field> <persistence-type>Container</persistence-type> <cmp-version>2.x</cmp-version> <reentrant>False</reentrant> <cmp-field>

Java certification success, Part 3: SCBCD

Page 47 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

<field-name>courseId</field-name> </cmp-field> <cmp-field> <field-name>trainer</field-name> </cmp-field> </entity> ...

CMP relationships
CMRs are defined in terms of the local interfaces of the related entity beans. Relationships may be one-to-one, one-to-many, or many-to-many relationships, and may be either bi-directional or unidirectional. An entity bean that does not have a local interface can have only unidirectional relationships from itself to the other entity beans. The relationships are defined in the <relationships> section of the deployment descriptor. Within the <relationships> element, each entity-to-entity relationship is defined in a separate <ejb-relation> element, as illustrated below. Here EmployeeEJB and AddressEJB share a one-to-one unidirectional relationship:
<ejb-relation> <ejb-relationship-role> <ejb-relationship-role-name>Employee</ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>EmployeeEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>address</cmr-field-name> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name>Address</ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>AddressEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> </ejb-relation>

Every <ejb-relation> element has exactly two <ejb-relationship-role> elements, one for each participant. Each relationship role refers to an entity bean by means of an <ejb-name> element

Page 48 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

contained in the <relationship-role-source> element. The <multiplicity> element describes the multiplicity of the role that participates in a relation (One or Many). If one bean maintains a relationship to another bean, the reference is declared using a <cmr-field> element. A CMR field can use only the local interface of the referenced bean. For every <cmr-field> element, there must be a pair of abstract accessor methods in the bean class, as shown below. The name of the accessor method is determined by the name of the relationship field in the deployment descriptor.
public abstract class EmployeeBean implements EntityBean { public abstract void setAddress(AddressLocal address); public abstract AddressLocal getAddress(); }

Assigning relationships
When we reassign relationships, the container ensures that data integrity is maintained by using the multiplicity defined for both beans. Consider the following relationships between instances of Employee and Address entity beans.

It is not possible to share a single Address bean between two Employee beans because they share a one-to-one relationship. Now suppose we make the assignment employeeB.setAddress(employeeA.getAddress());, as shown below:

Java certification success, Part 3: SCBCD

Page 49 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Here the "Address 1" object reference was moved from "Employee A" to "Employee B." Now consider the relationships between different instances of the Department bean and the Employee bean. The multiplicity for Employee is "Many" and for Department is "One."

Now let us make the assignment employeeC.setDepartment(employeeA.getDepartment()); , as shown below:

Page 50 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Note that in this case, the "Department 1" object reference is shared between Employee A, B, and C, instead of being moved.

Cascade deletes
The removal of an entity object can cause the removal of a related entity object, if the <cascade-delete> element is specified for the target bean. The entity that uses the <cascade-delete> element must have a multiplicity of "One" in the relationship. The container calls the ejbRemove() method on the target bean instance due to the cascade delete operation and then removes its data from the database. Consider the relationship between an employee and his profile. Because <cascade-delete> has been specified for the ProfileEJB bean, removal of the EmployeeEJB bean instance will cause the container to automatically delete the associated Profile instance also:
<ejb-relation> <ejb-relationship-role> <ejb-relationship-role-name>Employee</ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>EmployeeEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>profile</cmr-field-name> </cmr-field> </ejb-relationship-role>

Java certification success, Part 3: SCBCD

Page 51 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

<ejb-relationship-role> <ejb-relationship-role-name>Profile</ejb-relationship-role-name> <multiplicity>One</multiplicity> <cascade-delete/> <relationship-role-source> <ejb-name>ProfileEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> </ejb-relation>

Sample questions
Question 1: What are the valid types for the CMR field of an entity bean? Choices: ° ° ° ° ° ° A. Primitive types B. Collection C. Set D. Entity bean's local interface E. java.lang.String F. java.lang.Integer

Correct choice: B, C, and D Explanation: The get() method for a CMR field in the entity bean class must return either the local interface of the entity bean or a collection (either java.util.Collection or java.util.Set) of the same, so these are the valid types of CMR fields of an entity bean. The set() method for the relationship must take as an argument the entity bean's local interface or a collection of the same. Also note that the <cmr-field-type> element must be specified in the deployment descriptor if the type of the <cmr-field> is java.util.Collection or java.util.Set. For more information, refer to section 10.3.2 of the EJB 2.0 specification (see Resources on page113 ).
Page 52 of 115 Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Question 2: There are two entity beans, BeanA and BeanB, in a one-to-one unidirectional relationship. In addition, there are two references, ba1 and ba2, to instances of BeanA and two references, bb1 and bb2, to instances of BeanB. Moreover, ba1 is linked to bb1 and ba2 is linked to bb2. If the statement ba1.setBean2(ba2.getBean2()) is executed, which of the following expressions will be true? Choices: ° ° ° ° ° ° A. ba2.getBean2() != null B. ba2.isIdentical(bb1.getBean1()) C. bb1.isIdentical(ba2.getBean2()) D. bb2.isIdentical(ba1.getBean2()) E. ba1.isIdentical(bb2.getBean1()) F. ba1.getBean1() == null

Correct choice: D Explanation: First, let's examine what the relationships look like. We have two entity beans, Bean1 and Bean2, in a one-to-one unidirectional relationship. This means that one instance of Bean1 has a reference to one instance of Bean2, but the instance of Bean2 has no reference to the instance of Bean1. As the question states, ba1 is linked to bb1 and ba2 is linked to bb2. The statement ba1.setBean2(ba2.getBean2()) retrieves the Bean2 object that ba2 is referencing and assigns it to ba1. Because it is a one-to-one relationship, only one bean can have a reference to another, which means that after the execution of the above statement ba2 is not referencing anything. Thus, ba2.getBean2() returns null. Therefore, choice A is incorrect. Choices B and E are incorrect because the relationship is unidirectional and instances of Bean2 do not hold a reference to an instance of Bean1. Choice C is incorrect because after the execution of the above statement, ba2 does not refer to any instance of Bean2. Thus, ba2.getBean2() returns null. Choice D is correct because after the execution of the above statement the instance of Bean2 (bb2) that was previously referenced by ba2 is now referenced by ba1. Thus, this expression returns true.

Java certification success, Part 3: SCBCD

Page 53 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Choice F is incorrect because an instance of Bean1 does not have a reference to another instance of Bean1. Please refer to section 10.3.7.2 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
This section examined how to write CMP entity beans and describe their container-managed fields in the deployment descriptor. We discussed the rules and semantics to be followed when defining CMRs between entity beans, and we saw how the multiplicity defined for the relationship participants is significant when assigning bean relationships. Finally, you also learned how the removal of an entity bean can be cascaded to cause the removal of related entity beans.

Page 54 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 8. CMP entity bean lifecycle Overview
CMP entity beans support instance pooling, just like stateless session beans. They are also passivated and activated, but unlike the stateful session beans, the bean state is not serialized. The container interacts with the database when a new entity is to be created or deleted. Similarly, it manages the transactions and the synchronization of the bean state with the database. Let's examine the important events in the life of an entity bean instance and how the container interacts with the bean during these events.

State diagram
The state diagram of a CMP entity bean is shown below:

Java certification success, Part 3: SCBCD

Page 55 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Lifecycle events
The bean can be in one of the following states: ° ° ° Does-not-exist Pooled Ready

At first, the bean is in the Does-not-exist state. The bean has not yet been instantiated. The container instantiates the bean by calling the Class.newInstance() method on the bean class. Then an EntityContext object is passed by invoking the setEntityContext() method. Now the bean instance is in the Pooled state. In this state, the bean instance can service finder methods, select methods, and home business methods, because they do not require the bean to have an identity. The bean instance can service entity-specific client calls when it is in the Ready state. Two possible transitions from the Pooled to the ready state exist: through the ejbCreate<METHOD>(...) and ejbPostCreate<METHOD>(...) methods, or through the ejbActivate() method. The container might decide to remove a bean from the pool and allow it to be garbage collected. At this point, the unsetEntityContext() method is called on the bean instance. Let's discuss the different events involved in the state transitions of a bean instance. Client invokes a create() method on the bean home ° A bean instance is chosen from the pool and its corresponding ejbCreate<METHOD>() method is invoked. ° A primary key is created and a new record is inserted. ° The bean instance is associated with the EJB object. ° The corresponding ejbPostCreate<METHOD>() method of the bean is invoked. ° An EJB Object reference is returned to the client. ° Now the bean instance is in the Ready state.

Client invokes a finder method on the bean home ° A bean instance is chosen from the pool and its corresponding ejbFind() method is called. ° The ejbFind() method verifies if the entity exists in the database. ° If the entity exists, the bean instance returns the primary key to the bean

Page 56 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

° °

home. The container makes an EJB Object and returns its reference to the client. The bean instance remains in the Pooled state.

Client invokes a business method on the EJB Object ° A bean instance is chosen from the pool and assigned to the EJB Object. ° The ejbActivate() method is called. ° The CMP fields of the bean are synchronized with the database. ° The ejbLoad() method is called. ° The business method is delegated to the bean.

Container decides to passivate a bean instance ° The ejbStore() method is called on the bean instance. ° The persistent state of the bean is synchronized with the database. ° The ejbPassivate() method is called on the bean instance. ° The bean instance is disassociated from the EJB Object. ° The bean instance enters the Pooled state.

Client invokes the remove() method on the bean's EJB Object or EJB home ° The ejbRemove() method is invoked on the bean instance. ° The entity data is removed from the database. ° The EJB Object reference is invalidated. ° The bean instance enters the Pooled state.

Methods defined in javax.ejb.EntityBean
Let's now review the significance of the various callback methods defined in the EntityBean interface and the responsibilities of the bean provider and container in defining them. setEntityContext() The entity object identity is not available in the setEntityContext() method. The programmer can use this method to allocate any resources that are to be held by the instance for its lifetime.

Java certification success, Part 3: SCBCD

Page 57 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

The container passes a reference to the EntityContext interface to the entity bean instance as an argument to this method. The container invokes this method after it creates an instance and before it puts the instance into the pool of available instances. This method is executed within an unspecified transaction context. unsetEntityContext() The container invokes this method when the container wants to reduce the number of instances in the pool. After this method completes, the container must not reuse this instance. The programmer can use this method to free any resources that are held by the instance. The bean identity is not available during this method also. ejbCreate<METHOD>() The container invokes the ejbCreate<METHOD>() methods when a client invokes a matching create<METHOD>() method on the entity bean's home interface. The Bean Provider can use this method to initialize the instance in this method from the input arguments. He must not attempt to modify the values of CMR fields in this method because the primary key is not yet available. This method should return null. The ejbCreate<METHOD>>() methods and the subsequent database insertion operations execute in the same transaction context as the create<METHOD>() methods previously invoked. ejbPostCreate<METHOD>() The ejbPostCreate<METHOD>() methods have the same set of arguments as the corresponding ejbCreate<METHOD>() methods, but their return type is void. The entity object identity is available during the ejbPostCreate<METHOD>() method, so this method can be used to set the values of CMR fields of the bean. This method executes in the same transaction context as the corresponding ejbCreate<METHOD>() method. The container creates the primary key of the entity before it invokes the ejbPostCreate<METHOD>() method. ejbActivate() The ejbActivate() method is invoked on an entity bean instance after activation. The primary key of the associated entity object is available to the instance during this method. The bean can use this method to acquire additional resources that it needs while it is in the Ready state. The container invokes this method within an unspecified transaction context. ejbPassivate() The ejbPassivate() method is invoked when the container decides to

Page 58 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

disassociate the instance from an entity object identity. The primary key of the associated entity object is available to the instance during this method. The bean can use this method to release the resources that it acquired during the ejbActivate() method. The container invokes this method within an unspecified transaction context. ejbRemove() The ejbRemove() method is invoked in response to a client-invoked remove operation on the entity bean's home or component interface or as the result of a cascade-delete operation. The container synchronizes the state of the instance before it invokes the ejbRemove() method. The entity bean identity is available during this method. After ejbRemove() returns, the container removes the entity bean instance from all the relationships in which it participates and then removes its persistent data. The ejbRemove() method and the database delete operations are performed in the transaction context of the invoked remove() method. The bean instance is in the Ready state when ejbRemove() is invoked and it will be entered into the pool when the method completes. ejbLoad() The ejbLoad() method is called when the container needs to synchronize the state of an enterprise bean instance with the entity object's persistent state. This method can be used to recompute or initialize the values of any instance variables that depend on the entity bean's persistent state. This method executes in the transaction context determined by the transaction attribute of the business method that triggered it. ejbStore() The ejbStore() method is called when the container needs to synchronize the state of the entity object in the database with the state of the enterprise bean instance. This method is invoked in the same transaction context as the previous ejbLoad() or ejbCreate() method invoked on the instance. The Bean Provider can use the ejbStore() method to update the instance using the accessor methods before its persistent state is synchronized. ejbFind<METHOD>() The ejbFind<METHOD>() methods are generated at the entity bean deployment time using the container provider's tools. The container invokes the ejbFind<METHOD>() method on an instance when a client invokes a matching find<METHOD>() method on the bean home. The method is invoked

Java certification success, Part 3: SCBCD

Page 59 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

on a pooled entity instance, which remains pooled even after the method call. This method is invoked in the transaction context of the matching find<METHOD>() method. ejbSelect<METHOD>() The ejbSelect<METHOD>() methods are not directly exposed to the client in the home or component interface because they are for the internal use of the bean. They are declared as abstract by the bean provider and their implementation is generated at deployment time using the container provider's tools. These methods are typically called within a home or business method. They execute in the transaction context determined by the transaction attribute of the invoking method. ejbHome<METHOD>() The ejbHome<METHOD>() methods are invoked when the container selects the instance to execute a matching client-invoked home business method. The pooled instance, which is chosen for the method execution, remains in the pooled state after the execution of the home method. It is invoked in the same transaction context as the triggering home method. The entity Bean Provider provides the implementation of the ejbHome<METHOD>(...) method. as an EJB-QL expression in the deployment descriptor. Because the bean identity is not available within this method, the bean must not attempt to access its persistent state or relationships using the accessor methods.

Sample questions
Question 1: Select all the methods of an entity bean class that have a matching method in their home interface. Choices: ° ° ° ° ° A. ejbCreate<METHOD>() B. ejbSelect<METHOD>() C. ejbLoad<METHOD>() D. ejbRemove<METHOD>() E. ejbFind<METHOD>()

Correct choice: A and E

Page 60 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Explanation: Choices A and E are correct because ejbCreate<METHOD>() must have a matching create<METHOD>() method in the home interface. Similarly, ejbFind<METHOD>() must have a matching find<METHOD>() method in the home interface. Choice B is incorrect because the ejbSelect<METHOD>() methods are internal to the bean class and have no matching method in the home interface. They are usually invoked by an ejbHome<METHOD>() method or another method internal to the bean class and not by the client. Choices C and D are incorrect, as the ejbLoad() and ejbRemove() methods must not have any <METHOD> suffix. These methods are inherited from the javax.ejb.EntityBean interface and must be implemented by the entity bean class. Please refer to sections 10.5.2 and 10.5.3 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: It is mandatory that certain resources held by an entity bean be released when the bean leaves the instance pool to be garbage collected. Which of the following methods should contain the code for doing this? Choices: ° ° ° ° A. ejbRemove() B. ejbPassivate() C. unsetEntityContext() D. finalize()

Correct choice: C Explanation: The ejbRemove() method is invoked when the client application invokes the remove() method on the bean's EJBObject or EJBHome. It notifies the entity bean instance that its data is about to be removed from the database. The bean then transitions into the Pooled state. So choice A is incorrect. The ejbPassivate() method is invoked when a bean instance is disassociated from its EJBObject and is moved to the Pooled state. The method that is called when the bean instance moves from the instance pool to
Java certification success, Part 3: SCBCD Page 61 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

be garbage collected is unsetEntityContext(). After this method is called, the bean instance is eligible for garbage collection. Therefore, choice C is correct. The finalize() method should not be used to release the resources because it might not be called at all. Hence, choice D is incorrect. For more information, refer to section 10.5 of the EJB 2.0 specification (see Resources on page113 ).

Summary
This section traced the lifecycle of a CMP entity bean. We have seen that creation, passivation, activation, and removal of entity beans are significantly different from that of session beans. You should be aware of the exact sequence of events for each state transition of the bean instance. We also discussed the methods defined in the bean class and the responsibilities of the Bean Provider and container in each case.

Page 62 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 9. Entity beans EntityContext interface
The EntityContext interface allows an entity bean instance to access its container-provided runtime context. After a bean instance is created, the container invokes the setEntityContext() method on the instance, passing a reference to its EntityContext. As the bean instance is switched between EJB Objects by the container, the information obtained from EntityContext (such as the primary key) is subject to change. The EntityContext interface extends javax.ejb.EJBContext, which is also extended by the SessionContext, used by session beans. EntityContext methods Let us examine the methods that can be invoked by the entity bean on its EntityContext reference. Methods defined in EntityContext are as follows: ° EJBLocalObject getEJBLocalObject(), which returns a reference to the local component interface of the bean instance. EJBObject getEJBObject(), which returns a reference to the remote component interface of the bean instance. Object getPrimaryKey(), which returns the primary key of the EJB Object that is currently associated with this bean instance. It is the only method in the EntityContext interface that is not declared in the SessionContext interface because session beans cannot have primary keys.

°

°

Methods inherited by EntityContext from EJBContext are as follows: ° EJBHome getEJBHome(), which returns a reference to the entity bean's remote home interface. EJBLocalHome getEJBLocalHome(), which returns a reference to the entity bean's local home interface. javax.security.Principal getCallerPrincipal(), which returns an instance of a java.security.Principal that identifies the invoker of

°

°

Java certification success, Part 3: SCBCD

Page 63 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

the method. ° boolean isCallerInRole(String rolename), which returns true if the caller of the entity bean instance has a particular role. void setRollbackOnly(), which marks the current transaction for rollback. boolean getRollbackOnly(), which allows the bean instance to test if the current transaction has been marked for rollback. javax.transaction.UserTransaction getUserTransaction(), which returns an instance of a javax.transaction.UserTransaction interface. Entity bean instances must not call this method because they do not support BMT demarcation.

°

°

°

Operations allowed in EntityBean methods
Let's look at which operations are allowed to be performed in the methods defined in an entity bean. If an entity bean instance attempts to invoke a method of the EntityContext interface, and access is not allowed, the container throws a java.lang.IllegalStateException exception. You are not allowed to invoke the getEJBObject(), getEJBLocalObject(), and getPrimaryKey() methods in the methods in which there is no entity object identity associated with the instance, which include setEntityContext(), unsetEntityContext(), ejbCreate<METHOD>(), and ejbHome<METHOD>(). When a new entity is created, the bean identity and primary key are not available until the ejbPostCreate<METHOD>() method is invoked. The getCallerPrincipal() and isCallerInRole() methods of EntityContext are not allowed to be invoked in methods in which the container does not have a client security context, which include the setEntityContext(), unsetEntityContext(), ejbPassivate(), and ejbActivate() methods. The getRollbackOnly() and setRollbackOnly() methods, which allow getting and setting of the transaction status, are not allowed in methods for which the container does not have a meaningful transaction context, which include the setEntityContext(), unsetEntityContext(), ejbPassivate(), and ejbActivate() methods.

Page 64 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Accessing resource managers and enterprise beans is not allowed in the ejbPassivate() and ejbActivate() methods because there is no meaningful transaction context or client security context. The getEJBHome() and getEJBLocalHome() methods can be invoked in all the bean methods except the constructor.

Primary keys
A primary key is an object that uniquely identifies an entity bean within its EJB home. If two entity EJB Objects from the same home have the same primary key, they are considered identical. A primary key can be of two types: Single field keys or composite keys. A single field primary key maps to a single persistence field in the entity bean. A composite primary key maps to more than one persistence field in the entity bean. A primary key class has the following requirements: ° ° ° Must be a legal Value Type in RMI-IIOP Must provide suitable implementation of the hashCode() and equals() methods Must be serializable and public

Single field primary keys We can use a single CMP field of the primary key by declaring the field name and the class name in the deployment descriptor. Typically, String and wrapper classes are used as single field primary keys because they are atomic. The <primkey-field> element of the deployment descriptor specifies the container-managed field of the entity bean. The field type must be the same as the primary key type. The <prim-key-class> element contains the fully qualified name of an entity bean's primary key class. For example, we have the "custId" CMP field as the primary key for the CustomerBean entity bean shown below:
public abstract class CustomerBean implements EntityBean { // Accessor methods in the bean class for the primary key public abstract Integer getCustId(); public abstract void setCustId(Integer id); ...

Java certification success, Part 3: SCBCD

Page 65 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

} // Specifying the primary key details in the deployment descriptor <entity> ... <prim-key-class>java.lang.Integer</prim-key-class> <cmp-field><field-name>custId</field-name></cmp-field> <primkey-field>custId</primkey-field> ... </entity>

Composite primary keys A composite primary key is made up of the CMP fields of the bean. The class must be public and must have a public constructor with no parameters. All fields in the primary key class must be declared as public, and their names must correspond to the entity bean field names that comprise the key. The <primkey-field> element is not used for composite keys. The <prim-key-class> element contains the fully qualified name of an entity bean's primary key class. The following example shows the definition of a composite primary key:
public class StudKey implements Serializable { public String studentId; public String courseId; public StudKey() { } public StudKey(String studentId, String courseId) { this.studentId = studentId; this.courseId = courseId; } public boolean equals(Object obj) { if (obj==null || ! (obj instanceof StudKey)) return false; StudKey key = (StudKey) obj; return studentId.equals(key.studentId) &courseId.equals(key.courseId); } public int hashCode() { return studentId.hashCode() ^ courseId.hashCode(); } }

Undefined primary keys The bean developer can defer declaring the primary key to the deployer, which allows the deployer to choose a database-specific key at deployment time. The Bean Provider must specify the primary key class in the deployment descriptor as type java.lang.Object. The container generates the primary key value when the entity bean instance is created.

Page 66 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Sample questions
Question 1: Select all the methods in which the identity of an entity bean is not available. Choices: ° ° ° ° ° A. ejbHome<METHOD>() B. ejbRemove() C. ejbCreate<METHOD>() D. ejbLoad() E. setEntityContext()

Correct choice: A C, and E Explanation: Saying that the identity of an entity bean is available amounts to saying that the getEJBObject(), getEJBLocalObject(), and getPrimaryKey() methods can be successfully invoked (that is, without throwing an exception) on the entity context object. The methods from which these methods can be invoked are ejbPostCreate<METHOD>(), ejbRemove(), ejbActivate(), ejbPassivate(), ejbLoad(), ejbStore(), and business methods. The question is about the methods in which the bean identity is NOT available. Therefore, choices A, C, and E are correct, and the remaining choices are incorrect. Please refer to section 10.5.5 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: What are the requirements for a primary key class that maps to multiple fields of an entity bean class? Choices: ° A. The primary key class must be private and be an inner class of the

Java certification success, Part 3: SCBCD

Page 67 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

entity bean class. ° B. The primary key class must be public and abstract because the container will be responsible for providing an implementation of the primary key classes. C. All fields of the primary key class must follow the JavaBeans conventions -- that is, the fields must be private, and public accessor or mutator methods must be provided. D. All fields of the primary key class must be declared public (and thus break the encapsulation of the primary key class). E. The container-managed field names of the entity bean declared in the deployment descriptor can be used as field names in the primary key class. F. ba1.getBean1() == null

°

°

°

°

Correct choice: D and E Explanation: Choice A is incorrect because the primary key class must be declared public and not private. Choice B is incorrect because the primary key class does not need to be declared abstract. The container should be allowed to use the primary class without having to extend it. Choice C is incorrect because there is no such requirement. All fields of the primary key class must be declared public, even if this means that the encapsulation of the class is broken. Hence, choice D is correct. Choice E is also correct because the primary key class is not allowed to declare fields having names that are different from the names of the container-managed fields declared in the <cmp-field> elements in the deployment descriptor. Please refer to section 10.8 of the EJB 2.0 specification for further details (see Resources on page113 ).

Page 68 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Summary
This section covered the methods defined in the EntityContext interface, which is the interface the entity bean instance uses to interact with the container. Some operations may require a valid transaction context or security context to be available when they are invoked, while some others might work only for CMTs. Hence, it is important to understand which operations are allowed to be performed within each callback method of the bean and why. We also discussed the rules regarding the primary keys of entity beans and how to define the single field and composite keys.

Java certification success, Part 3: SCBCD

Page 69 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 10. EJB-QL Purpose of EJB-QL
EJB-QL is a query specification language for the finder and select methods of CMP entity beans. This language is portable across databases and data schemas. It is possible to parse and validate EJB-QL queries before entity beans are deployed because the language is defined in terms of the abstract persistent schema of the entity beans. These queries are written by the entity Bean Provider in the deployment descriptor. Container tools then translate these queries into the target language of the underlying data store. EJB-QL queries can be used in two different ways: ° ° As queries for selecting entity objects through finder methods defined in the home interface As queries for selecting entity objects or other values derived from an entity bean's abstract schema type through select methods defined on the entity bean class

Using EJB-QL
Basic syntax An EJB-QL query is a string that consists of the following three clauses: ° ° ° A SELECT clause, which determines the type of the objects or values to be selected A FROM clause, which provides declarations that designate the query domain An optional WHERE clause, which may be used to restrict the results returned by the query

All standalone identification variables in the SELECT clause must be qualified by the OBJECT operator. For example, the following query statement returns all the customers:
SELECT OBJECT(c) FROM Customer c

EJB-QL also allows SELECT clauses to return CMP or CMR fields. Paths can navigate over one or more CMR fields to end at either a CMR or CMP

Page 70 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

single-valued field. In the example below, name is a CMP field, and address is a CMR field that contains the city CMP field:
SELECT c.name FROM Customer c SELECT c.address.city FROM Customer c

The IN operator allows the representation of individual elements in a collection-valued CMR field. The following query returns the phone numbers of all the customers:
SELECT OBJECT (p) FROM Customer c, IN (c.phones) p

Note that path expressions cannot navigate beyond CMP fields. The following query is invalid because city is a CMP field of the Address bean: SELECT c.address.city.name FROM Customer c The SELECT clause cannot return multi-valued expressions, so the following query is invalid:
SELECT o.lineItems FROM Order o

The following query is invalid because navigating across a collection-based relationship field is not allowed:
SELECT c.phones.no FROM Customer c

Conditional expressions We can use conditional expressions in the WHERE clause to restrict the results of the query. The following query returns only the customers based in California:
SELECT OBJECT(c) FROM Customer c WHERE c.address.state = "CA"

Likewise, the following query returns only the customers who have placed orders:
SELECT OBJECT(c) FROM Customer WHERE c.orders IS NOT EMPTY

An EJB-QL query may have parameters that correspond to the parameters of the finder or select method for which it is defined, as shown in the following example:

Java certification success, Part 3: SCBCD

Page 71 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

SELECT DISTINCT OBJECT(c) FROM Customer c WHERE c.age = ?1 AND c.name = ?2

Here the age and name of the customer are passed as parameters to the query. The DISTINCT keyword is used to specify that duplicate values must be eliminated from the query results. BETWEEN expressions The BETWEEN clause is used to specify a range of values. It may be used only on numeric primitives and their wrappers. It is inclusive of the upper and lower limits. The following query returns all the customers between the ages of 20 and 30:
SELECT OBJECT(c) FROM Customer c WHERE c.age BETWEEN 20 AND 30

IN expressions The IN operator in the WHERE clause tests for membership in a list of literal string values:
SELECT OBJECT(c) FROM Customer WHERE c.address.state IN ("TX","CA") SELECT OBJECT(c) FROM Customer WHERE c.address.state NOT IN ("TX","CA")

Here, the first query returns the customers from the given states and the second returns those who are not from these states. LIKE expressions The LIKE operator allows you to select CMP String fields that match a given pattern. The "%" symbol stands for any sequence of characters, while the "_" symbol stands for a single character.
SELECT OBJECT(c) FROM Customer c WHERE address.phone LIKE "45%3"

The query returns customers whose phone numbers are "453" and "45993," but not "4534": The following query returns a customer whose name is "rose," but not "roose."
SELECT OBJECT(c) FROM Customer c WHERE c.name LIKE "ro_e"

Page 72 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Using EJB-QL with finder methods
Finder methods are defined in the home interface of an entity bean and return a single entity object or a collection of entity objects. Every finder method must be mapped to an EJB-QL query using the query element in the deployment descriptor. The query element has two sub-elements: <query-method> and <ejb-ql>. The <query-method> element identifies the finder method, and the <ejb-ql> element declares the EJB-QL statement. Every entity bean referenced in an EJB-QL statement must have an identifier known as "abstract schema name," which is declared by the <abstract-schema-name> element. Consider the following home interface definition:
public interface CustomerHomeLocal extends EJBLocalHome{ public CustomerLocal findByPrimaryKey(Integer primaryKey)throws FinderException; public Collection findByCity(String city) throws FinderException; }

EJB-QL declarations are not allowed for findByPrimaryKey() methods. However, the findByCity() method needs to be mapped to a query element as shown below:
<entity> <ejb-name>CustomerEJB</ejb-name> ... <abstract-schema-name>Customer</abstract-schema-name> <cmp-field><field-name>city</field-name></cmp-field> ... <query> <query-method> <method-name>findByCity</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> SELECT OBJECT(c) FROM Customer c where c.city = ?1 </ejb-ql> </query> </entity>

Java certification success, Part 3: SCBCD

Page 73 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Using EJB-QL with select methods
A select method is a special type of query method, not directly exposed through the client view. It is declared as abstract in the entity bean class and can return values that correspond to any CMP or CMR field type. Like find methods, select methods can declare zero or more arguments. An ejbSelect() method definition is shown in the following example:
public abstract class AddressBean implements EntityBean{ public abstract Collection ejbSelectAll() throws FinderException; }

The select methods are not declared in the home interfaces, so the ejbSelect() method names in the bean class are mapped to the queries.
<query> <query-method> <method-name>ejbSelectAll</method-name> <method-params/> </query-method> <result-type-mapping>Remote</result-type-mapping> <ejb-ql> SELECT OBJECT(a) FROM Address a </ejb-ql> </query>

By default, an ejbSelect<METHOD>() method is assumed to return EJBLocalObject or a collection of EJBLocalObjects. If the ejbSelect<METHOD>() method returns an EJBObject or collection of EJBObjects, the Bean Provider must specify the value of the <result-type-mapping> element as Remote. An ejbSelect<METHOD>() method is not based on the identity of the entity bean instance on which it is invoked, so it can be used to query across all the entity beans declared in the same deployment descriptor.

Sample questions
Question 1: Select all the expressions that are semantically equivalent to the BETWEEN

Page 74 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

expression given below:
person.age BETWEEN 20 and 25

(Assume that person is an identification variable identifying a bean that has a CMP field called age.) Choices: ° ° ° ° A. person.age B. person.age C. person.age D. person.age > 20 AND person.age < 25 >= 20 AND person.age < 25() > 20 AND person.age <= 25 >= 20 AND person.age <= 25

Correct choice: D Explanation: In EJB-QL, BETWEEN expressions always include the values at the limits. In this case, BETWEEN 20 and 25 really means any values between 20 and 25, both inclusive. Therefore, the only correct choice is D. Please refer to section 11.2.7.7 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: Which of the following statements about EJB-QL are correct? Choices: ° ° ° ° A. EJB-QL queries are portable across databases, data schemas, and EJB containers. B. EJB-QL queries can be used to insert records into the database. C. The SELECT clause must not use the OBJECT operator to qualify path expressions. D. SELECT clauses may return a single or collection-based CMR field.

Correct choice: A and C Explanation:

Java certification success, Part 3: SCBCD

Page 75 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

EJB-QL uses the abstract persistence schema of entity beans, including their relationships, for its data model. This makes the queries portable across EJB containers. At deployment time, the EJB-QL statements are translated into native data access code, so they are independent of the underlying data store structure and schema. Thus, choice A is correct. EJB-QL queries can only fetch data from the database; they cannot be used for updates and insertions. So choice B is incorrect. All standalone identification variables in the SELECT clause must be qualified by the OBJECT operator. However, the SELECT clause must not use the OBJECT operator to qualify path expressions. So choice C is correct. EJB-QL allows SELECT clauses to return any CMP or single CMR field. However, the path expressions in these clauses must not end with a collection-based relationship field. So choice D is incorrect. For more information, refer to section 11 of the EJB 2.0 specification (see Resources on page113 ).

Summary
This section demonstrated how to use EJB-QL queries to access the data required by the finder and select methods of an entity bean. We discussed the correct and incorrect syntaxes for an EJB-QL query and how to define such queries in the deployment descriptor. We reviewed how the results of the query can be restricted using conditional expressions, BETWEEN expressions, LIKE expressions, and comparison expressions.

Page 76 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 11. MDB component contract Message-driven beans
Message-driven beans (MDBs) are asynchronous JMS message consumers. They do not have home or component interfaces because clients never call them directly. A client accesses it by sending messages to the JMS destination (Queue or Topic) to which the bean listens. The client does not need to wait for the bean instance to receive the message or process it. After sending the message, the client can continue doing its job. However, there is no guarantee that the bean will receive the messages in the same order in which they have been sent.

MDB lifecycle
The lifetime of an MDB instance is controlled by the container. Only two states exist: Does not exist and Ready, as illustrated in the following figure:

The life of an MDB instance starts when the container invokes newInstance() on the MDB class to create a new instance. Next, the container calls setMessageDrivenContext() followed by ejbCreate() on the instance. The bean then enters the Ready state and is ready to consume messages. When a message arrives for the bean, the container invokes the onMessage() method of one of the available instances, passing a Message object in argument. Messages can be consumed and processed concurrently by using
Java certification success, Part 3: SCBCD Page 77 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

multiple instances of the same type. The container invokes ejbRemove() on the bean instance when it no longer needs the instance. The bean instance can perform clean up operations here.

Interfaces and methods
The MDB must implement the javax.ejb.MessageDrivenBean and javax.jms.MessageListener interfaces. MessageDrivenBean The MessageDrivenBean interface defines lifecycle event notification methods invoked by the container on the bean instance. The methods defined by this interface are as follows: ° ° void setMessageDrivenContext(MessageDrivenContext ctx) void ejbRemove()

The setMessageDrivenContext() method, which is invoked at the beginning of the bean lifecycle, provides the MDB instance with a reference to its MessageDrivenContext. The ejbRemove() method is called at the end of the bean lifecycle, before it is garbage collected. MessageListener A MessageListener object is used to receive asynchronously delivered messages. The only method defined by this interface is void onMessage(Message message). It is called by the bean's container when a message has arrived for the bean to service. It contains the business logic that handles the processing of the message. MessageDrivenContext The MessageDrivenContext interface gives the MDB instance access to the instance's runtime context maintained by the container. The context object remains associated with the instance for the lifetime of the instance. This interface contains only methods inherited from EJBContext. The methods of MessageDrivenContext that are allowed to be called by

Page 78 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

MDBs are as follows: ° ° ° public boolean getRollbackOnly(), which tests whether the transaction has been marked for rollback public void setRollbackOnly(), which marks the current transaction for rollback public UserTransaction getUserTransaction(), which returns the UserTransaction reference

The getRollbackOnly() and setRollbackOnly() methods must be invoked only in the onMessage() method. They are onlyfor MDBs using CMT demarcation. The getUserTransaction() method can be invoked in the ejbCreate(), ejbRemove(), and onMessage() methods. The getUserTransaction() method is only for beans using BMT demarcation.

Configuring the MDB
We need to configure some elements in the deployment descriptor to enable the MDB to listen to JMS messages. JMS destinations can be Queues or Topics. The <message-driven-destination> element indicates whether an MDB is intended for a Queue or a Topic. The Bean Provider specifies the <message-driven-destination> element to advise the Deployer whether to associate the MDB with a Queue or a Topic. Durable topic subscriptions, as well as queues, ensure that messages are not missed even if the EJB server is not running. The <subscription-durability> element specifies whether a JMS topic subscription is intended to be durable or non-durable. The following example illustrates the deployment descriptor configuration for an MDB:
<message-driven> <display-name>My Message Driven Bean</display-name> <ejb-name>Mdb1</ejb-name> <ejb-class>MyMDB</ejb-class> <transaction-type>Container</transaction-type> <message-driven-destination> <destination-type>javax.jms.Topic</destination-type> <subscription-durability>NonDurable</subscription-durability>

Java certification success, Part 3: SCBCD

Page 79 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

</message-driven-destination> </message-driven>

The JMS message service expects the container to acknowledge if a message has been successfully delivered to the MDB. If an acknowledgement is not received, the JMS service resends the same message. If the bean uses CMT transaction demarcation, the message acknowledgment is handled automatically as a part of the transaction commit. For beans using BMT transaction demarcation, the Bean Provider can indicate in the <acknowledge-mode> element whether JMS AUTO_ACKNOWLEDGE or DUPS_OK_ACKNOWLEDGE should be used. Using AUTO_ACKNOWLEDGE automatically acknowledges the successful delivery of a message. Using DUPS_OK_ACKNOWLEDGE instructs the container to lazily acknowledge the delivery of messages, which makes the server more efficient at the risk of duplicate messages.

Responsibilities of the Bean Provider
The Bean Provider needs to follow these guidelines to ensure that an MDB can be deployed in any EJB container. Requirements of the MDB class ° The class must implement MessageDrivenBean and MessageListener interfaces. ° The class must be declared public but neither final nor abstract. ° The class must have a public constructor that takes no arguments. ° The class must not declare the finalize() method. ° The class must implement the ejbCreate() method.

Requirements of the ejbCreate() method ° The method must be public and must not take any arguments. ° The return type must be void. ° The method must neither be declared final nor static. ° The throws clause must not contain any application exception types.

Requirements of the onMessage() method ° The method must be public and must take a single argument of type javax.jms.Message. ° The return type must be void. ° The method must neither be declared final nor static.

Page 80 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

The throws clause must not contain any application exception types.

Requirements of the ejbRemove() method ° The method must be declared as public. ° The method must neither be declared final nor static. ° The return type must be void. ° The method must have no arguments. ° The throws clause must not define any application exception types.

Responsibilities of the container provider
The container provider is responsible for providing the deployment tools and for managing the MDB instances at runtime. The container must ensure that the bean instances are always thread-safe. The container may generate additional classes when the MDB is deployed. It must support the deployment of an MDB as the consumer of a JMS queue or a durable subscription. The container must also follow the rules with respect to transaction scoping, security checking, and exception handling.

Sample questions
Question 1: Which of the following methods of the MessageDrivenContext interface are available for use by the MDBs? Choices: ° ° ° ° A. getCallerPrincipal() B. getEJBHome() C. getRollbackOnly() D. isCallerInRole()

Correct choice:

Java certification success, Part 3: SCBCD

Page 81 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

C Explanation: The MDBs do not have a home or component interface. The getEJBHome() method will throw an exception if invoked, because an MDB does not have a home interface. MDBs are anonymous, that is they don't have a visible client identity. So the getCallerPrincipal() and isCallerInRole() methods, which need the security context of the caller, cannot be invoked. However, MDBs are transactional, so the getRollbackOnly() method can be invoked. For more information, refer to section 15.4.3 of the EJB 2.0 specification (see Resources on page113 ). Question 2: Which are the interfaces that must be implemented by an MDB? Choices: ° ° ° ° ° A. MessageDrivenObject B. MessageDrivenBean C. MessageListener D. MessageDrivenContext E. MSListener

Correct choice: B and C Explanation: The MessageDrivenBean and MessageListener interfaces should be implemented by any MDB class. The onMessage() method is defined in the MessageListener interface. This method passes the messages to the MDB by the container. The MessageDrivenBean interface defines two callback methods -- setMessageDrivenContext() and ejbRemove(). The setMessageDrivenContext() method is called at the beginning of the MDB's lifecycle and provides the bean with a reference to its MessageDrivenContext interface. The MessageDrivenContext interface extends the EJBContext interface. One of these methods is setRollbackOnly(). Only Mandatory and Never may cause the EJB container to throw an exception, so the remaining options are incorrect.

Page 82 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

For more information, refer to section 15.4 of the EJB 2.0 specification (see Resources on page113 ).

Summary
This section covered message-driven beans. The main point to remember about MDBs is that they do not expose a client view. Therefore, their lifecycle is entirely controlled by the container, they do not have component or home interfaces, and the methods that can be invoked on the MessageDrivenContext are limited. Also note that MDB methods must not throw application exceptions, because there aren't any clients to handle them. For this objective, we do not need to know much about the Java Messaging Service, but it is necessary to be aware of the MDB configuration elements in the deployment descriptor.

Java certification success, Part 3: SCBCD

Page 83 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 12. Transactions Overview
Transactional systems ensure that a unit of work either fully completes or is fully rolled back. The EJB architecture supports distributed transactions, but not nested ones. In nested transactions, a new transaction can be started, while a transaction is currently active. In EJB development, the Bean Provider can choose between using programmatic transaction demarcation in the enterprise bean code (BMT demarcation) or declarative transaction demarcation performed automatically by the EJB container (CMT demarcation). A session bean or an MDB can use BMT or CMT, but not both at the same time. An entity bean can use only CMT.

Container-managed transactions
The EJB container is responsible for managing transaction boundaries in the case of a CMT bean. When a client calls a method on an enterprise bean, the new method can run in the caller's transaction, start a new transaction, or run without a transaction. The action taken by the EJB container in this case is decided by the transaction attribute defined for the method. Transaction attribute basics Transaction attributes must be given for business methods in the case of both entity and session beans. They must not be specified for the methods of a session bean's home interface because these methods are not considered as part of a client's transaction. This rule, however, is not the case for entity beans, in which home interface methods like create() and remove() involve database operations and are hence transactional. For an MDB, the transaction attribute can only be specified for the bean's onMessage() method, because there is no client view. The six possible transaction attributes are Required, RequiresNew, NotSupported, Supports, Mandatory, and Never. Let's look at how each of these influences the transactional behavior of the method: ° Required: If the EJB client is not associated with a transaction, the container will automatically begin a new transaction for the bean method.

Page 84 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Otherwise, it uses the existing client transaction. ° RequiresNew: The container always creates a new transaction before invoking a method on the bean. NotSupported: The transactional context of the calling client is not propagated to the enterprise bean. Instead, the client transaction is suspended and the bean method runs within an unspecified transaction context. Supports: If the client is associated with a transaction context, the bean runs within the same transaction context. Otherwise, the bean method runs within an unspecified transaction context. Mandatory: If a remote client invokes a bean method without a meaningful transaction context, the container throws TransactionRequiredException. If a local client invokes a bean method without a meaningful transaction context, the container throws TransactionRequiredLocalException. Otherwise, the bean method runs within the client's transaction context. Never: If a remote client invokes a bean method with a meaningful transaction context, the container throws a java.rmi.RemoteException. If a local client invokes a bean method with a meaningful transaction context, the container throws a javax.ejb.EJBException. Otherwise, the bean method runs within an unspecified transaction context.

°

°

°

°

Restrictions on transaction attributes For MDBs, only the Required and NotSupported transaction attributes may be used because they have no calling clients and hence the other attributes do not apply. If an enterprise bean implements the SessionSynchronization interface, only the transaction attributes Required, RequiresNew, or Mandatory are allowed, to ensure that the method is participating in a transaction. For portable entity beans that use EJB 2.0 CMP also, only the Required, RequiresNew, or Mandatory transaction attributes must be used. CMT beans may use the setRollbackOnly() method on its EJBContext to mark a transaction for rollback, and the getRollbackOnly() method to test if a transaction has been marked for rollback. For these operations to work, the method in which they are invoked should be in a transaction, so its attribute must be Required, RequiresNew, or Mandatory. Roles and responsibilities

Java certification success, Part 3: SCBCD

Page 85 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

The Bean Provider must use the <transaction-type> element to declare whether the bean uses CMT or BMT demarcation. The Application Assembler uses the <container-transaction> element to define the transaction attributes. The Deployer is responsible for ensuring that the methods of the enterprise beans deployed with CMT demarcation have been assigned a transaction attribute. In the following example, all the methods of CustomerEJB have been given the transaction attribute Required, except the addBonus() method, which has been given the attribute Mandatory:
<enterprise-beans> <session> <ejb-name>CustomerEJB</ejb-name> ... <transaction-type>Container</transaction-type> </session> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>CustomerEJB</ejb-name> <method-name>*</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> <container-transaction> <method> <ejb-name>CustomerEJB</ejb-name> <method-name>addBonus</method-name> </method> <trans-attribute>Mandatory</trans-attribute> </container-transaction> </assembly-descriptor>

MDBs must not throw application exceptions, because they don't have any client view and they run asynchronously. If the methods are overloaded, the optional <method-params> and <method-param> elements allow you to identify the appropriate method. For example, if we want to specify a different transaction attribute for the addBonus(int) method, we can specify the method element as shown:
<method> <ejb-name>CustomerEJB</ejb-name> <method-name>addBonus</method-name> <method-params> <method-param> int </method-param> </method-params> </method>

Page 86 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Bean-managed transactions
In the case of BMTs, the bean itself manages transactions programmatically in the business methods. The Bean Provider uses the javax.transaction.UserTransaction interface to explicitly demarcate transactions. A bean instance that starts a transaction must complete the transaction before it starts a new one. In the following example, we first get a reference to the UserTransaction object, then start a new transaction by invoking the begin() method on it. We then add the transactional code, and finally we invoke the commit() method to end the transaction. To roll back the current transaction, we can invoke the rollback() method:
... UserTransaction ut = ejbContext.getUserTransaction(); ut.begin(); method1(); method2(); ... if(someSuccessCondition) ut.commit(); else ut.rollback();

A bean can also look up the UserTransaction object from the JNDI ENC, as shown below:
UserTransaction t = (UserTransaction) jndiContext.lookup("java:comp/UserTransaction");

Restrictions on using BMT A BMT bean can only run in the transactions that the bean has started itself. If a transactional client invokes the methods of a BMT bean, the incoming transaction is suspended. A stateful session bean instance may, but is not required to, commit a started transaction before a business method returns. A stateless session bean instance must commit a transaction before a business method returns, because the same instance is not dedicated for multiple method calls. An MDB instance must commit a transaction before the onMessage() method returns.

Java certification success, Part 3: SCBCD

Page 87 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

A BMT enterprise bean must not use the getRollbackOnly() and setRollbackOnly() methods of the EJBContext interface. Instead, it must use the getStatus() and setRollbackOnly() methods of the UserTransaction interface. Methods of UserTransaction The UserTransaction interface defines the following methods that are invoked by the bean to manage the transactions: ° void begin(): Creates a new transaction and associates it with the current thread. void commit(): Completes the transaction associated with the current thread. void rollback(): Rolls back the transaction associated with the current thread. void setRollbackOnly(): Modifies the transaction associated with the current thread such that the only possible outcome of the transaction is to roll back the transaction. Invoking this method is a signal to the other transaction participants that the transaction will never commit. int getStatus(): Returns the status of the transaction associated with the current thread. Using this method, the bean can find out if the setRollbackOnly() method has been invoked on the transaction. void setTransactionTimeout(int seconds): Modifies the timeout value that is associated with the transactions started by the current thread with the begin method.

°

°

°

°

°

Sample questions
Question 1: Which of the following statements about transactions in EJB 2.0 are true? Choices: ° A. The create() and remove() methods in session beans do not have

Page 88 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

° ° ° °

transaction attributes. B. Nested transactions are supported for BMT enterprise beans. C. Isolation levels can be specified for CMT session beans. D. A BMT MDB must begin and end a transaction within the onMessage() method. E. If the transaction attribute of a bean method is Mandatory and a remote client invokes it without a transaction, a TransactionMandatoryException is thrown.

Correct choice: A and D Explanation: The create() and remove() methods in session beans do not have transaction attributes, only the business methods have. So choice A is correct. Nested transactions and isolation levels are not supported in EJB 2.0, so choices B and C are incorrect. A BMT MDB must begin and end a transaction within the onMessage() method -- that is, a transaction cannot span multiple method calls. So choice D is correct. If the transaction attribute of a bean method is Mandatory and a remote client invokes it without a transaction, a TransactionRequiredException is thrown (there is no such exception as TransactionMandatoryException). So choice E is incorrect. Question 2: Which of the following transaction attributes may cause the container to throw an exception whenever the transaction context does not satisfy their requirements? Choices: ° ° ° ° ° ° A. Required B. RequiresNew C. Never D. Mandatory E. Supports f. NotSupported

Java certification success, Part 3: SCBCD

Page 89 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Correct choice: C and D Explanation: The transaction attribute Mandatory behaves the same way as the Required attribute when a client calls with a transaction context. However, if the client makes a call in an unspecified transaction context, the EJB container is required to throw the javax.transaction.TransactionRequiredException exception if the client is a remote client or the javax.ejb.TransactionRequiredLocalException if the client is a local client. The transaction attribute Never behaves the same way as the NotSupported attribute when a client calls without a transaction context. However, if the client makes a call within a transaction context, the EJB container is required to throw the java.rmi.RemoteException if the client is a remote client or the javax.ejb.EJBException if the client is a local client. Only Mandatory and Never may cause the EJB container to throw an exception, so the remaining options are incorrect. Therefore, C and D are correct, while A, B, E, and F are incorrect. Please refer to section 17.6.2 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
In this section, we discussed the effect of CMT demarcation as compared to that of BMTs in enterprise beans. It is important to remember that entity beans must not use BMT demarcation. Similarly, we saw which transaction attributes are applicable for MDBs, beans implementing SessionSynchronization interfaces, and so on. For each bean type, we need to be aware of the methods for which transaction attributes must be specified. Finally, we showed you the significance of the UserTransaction() methods, which enable BMT beans to programmatically manage transactions.

Page 90 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 13. Exceptions Application exceptions
An application exception is an exception defined in the throws clause of a method in the bean's home or component interface. An application exception class must be a direct or indirect subclass of java.lang.Exception, but neither of java.lang.RuntimeException nor java.rmi.RemoteException. These exceptions typically indicate application-level problems such as illegal values of the input arguments to a business method. They should be reported to the client without any modification. An application exception does not cause an automatic rollback of an ongoing transaction, and the client can continue to work with the bean instance.

System exceptions
A system exception is an exception that the client does not expect or is not expected to recover from. All unchecked exceptions as well as java.rmi.RemoteException belong to this category. System-level errors may be encountered during the execution of a session or an entity bean business method, an MDB onMessage() method, or a container callback method. Some examples include: ° ° ° ° ° Failure to obtain a database connection JNDI exceptions Unexpected RemoteException from invocation of other enterprise beans Unexpected RuntimeException JVM errors

When system exceptions are detected, the container will automatically roll back the existing transaction, if any. The bean instance will be discarded and the exception will be logged.

Responsibilities of the container provider
The Bean Provider expects the container to perform certain tasks when

Java certification success, Part 3: SCBCD

Page 91 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

exceptions are thrown. Let's examine these in detail for different situations. Application exceptions If the bean method is running in the context of the caller's transaction, the container re-throws the exception to the client. The client can continue working with the transaction but cannot commit the transaction if the bean instance has invoked the setRollbackOnly() method. This situation does not arise in the case of beans using BMT demarcation because transactions cannot propagate into a BMT bean. If the bean method runs in the context of a container-initiated transaction, the container attempts to commit the transaction and then re-throws the exception. However, if the bean instance has called setRollbackOnly(), then the container rolls back the transaction and re-throws the exception. For beans executing within an unspecified transaction context, the exception is simply re-thrown. MDBs must not throw application exceptions, because they don't have any client view and they run asynchronously. System exceptions For all bean types, system exceptions are logged, the existing transaction is marked for rollback, and the bean instance is discarded. If the bean was executing within a client-initiated transaction, the container throws TransactionRolledbackException to remote clients and TransactionRolledbackLocalException to local clients. This situation does not arise in the case of beans using BMT demarcation, because transactions cannot propagate into a BMT bean. For beans running in container-initiated transactions or within an unspecified transaction context, RemoteException is thrown to remote clients and EJBException to local clients. The container does not throw any exception in the case of MDBs, because they do not have any client view.

Responsibilities of the Bean Provider
Let's analyze the responsibilities of the Bean Provider with respect to exception handling. Application exceptions

Page 92 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

The application exception class must directly or indirectly extend java.lang.Exception, but not RuntimeException or RemoteException. If a business logic exception occurs in the bean code, the Bean Provider must throw it to the container as the appropriate application exception. Accordingly, the application exception must be declared in the throws clause of the business method in the component interface. If the Bean Provider catches an application exception and figures out that the transaction cannot be committed, he calls EJBContext.setRollbackOnly() for CMT beans or UserTransaction.setRollbackOnly() for BMT beans, before re-throwing the exception further. The Bean Provider must ensure that the bean instance is in a state such that a client's attempt to continue and/or commit the transaction does not result in the loss of data integrity.

°

°

°

System exceptions ° If the bean method encounters a RuntimeException or error, it should simply propagate the error to the container. ° If the bean method performs an operation that results in a checked exception that the client is not expecting, the bean method should wrap the original exception within a javax.ejb.EJBException and throw the latter to the container. javax.ejb.EJBException is a subclass of the java.lang.RuntimeException, and therefore does not have to be listed in the throws clauses of the business methods.

°

Common exceptions in EJB
Let's now explore some of the most common exceptions encountered in EJB programming. Standard application exceptions are: ° CreateException

Java certification success, Part 3: SCBCD

Page 93 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° ° ° °

DuplicateKeyException RemoveException FinderException ObjectNotFoundException

CreateException This exception can be thrown by the container to indicate a problem during the bean creation. This method must be declared in the throws clauses of all the create methods declared in an enterprise bean's home interface and all the ejbCreate<METHOD>() methods declared in the enterprise bean's class. DuplicateKeyException The javax.ejb.DuplicateKeyException exception is thrown if an entity object cannot be created because an entity with the same key already exists. This exception is thrown by the create methods defined in an entity bean's home interface. It is a subclass of javax.ejb.CreateException. RemoveException The javax.ejb.RemoveException exception may be thrown when attempting to remove a bean when the enterprise bean or the container does not allow it to be removed. FinderException The finder methods of an entity bean throw this exception to report a failure when finding the requested entity (or entities). It must be included in the throws clause of every finder method of the entity bean's home interface. ObjectNotFoundException The javax.ejb.ObjectNotFoundException exception is thrown by a single-entity finder method to indicate that the specified entity does not exist. It is a subclass of javax.ejb.FinderException. Some of the most common system exceptions are: ° ° ° ° ° EJBException IllegalStateException NoSuchEntityException TransactionRequired(Local)Exception TransactionRolledback(Local)Exception

EJBException The javax.ejb.EJBException exception is thrown by the bean to the

Page 94 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

container to report that the invoked business or callback method could not complete successfully because of some unexpected error. The container may throw it to local clients when it catches a system exception. It is a subclass of java.lang.RuntimeException. IllegalStateException This exception is also a subclass of java.lang.RuntimeException. The container throws this exception to the enterprise bean to signal that a method has been invoked at an illegal or inappropriate time, like calling setRollbackOnly() within a method executing in an unspecified transaction context. NoSuchEntityException The javax.ejb.NoSuchEntityException exception is thrown by an entity bean instance to report that the referenced entity was removed from the database. This exception may be thrown by ejbLoad(), ejbStore() and any business methods. It is a subclass of javax.ejb.EJBException. TransactionRequiredException/TransactionRequiredLocalException If a bean method marked with the Mandatory transaction attribute is invoked by a non-transactional client method, javax.transaction.TransactionRequiredException is thrown if the client is remote and javax.ejb.TransactionRequiredLocalException is thrown if the client is local. TransactionRolledbackException is a subclass of java.rmi.RemoteException and TransactionRolledbackLocalException is a subclass of javax.ejb.EJBException. TransactionRolledbackException/TransactionRolledbackLocalException If a client receives javax.transaction.TransactionRolledbackException or javax.ejb.TransactionRolledbackLocalException, the client knows for certain that the transaction has been marked for rollback. TransactionRolledbackException is a subclass of java.rmi.RemoteException, while TransactionRolledbackLocalException is a subclass of javax.ejb.EJBException.

Sample questions
Question 1:

Java certification success, Part 3: SCBCD

Page 95 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Which exception would a client receive if a javax.ejb.EJBException is thrown from a business method whose transaction attribute is Mandatory? Choices: ° ° ° ° ° ° A. javax.ejb.EJBException B. javax.ejb.TransactionRolledbackLocalException C. javax.transaction.TransactionRequiredException D. java.rmi.RemoteException E. javax.transaction.TransactionRolledbackException F. javax.ejb.TransactionRequiredLocalException

Correct choice: B Explanation: The critical point here is to understand the information contained in the question statement. First, we know that the bean throws a javax.ejb.EJBException, so we know we are dealing with a local client. Therefore, we can eliminate choices C, D, and E right away. Second, because the transaction attribute of the business method is Mandatory, we know for sure that a client transaction existed (otherwise the container would have thrown javax.ejb.TransactionRequiredLocalException), so choice F is incorrect. Because the javax.ejb.EJBException is not propagated, choice A is incorrect. When a business method that executes in the context of the local caller's transaction throws a javax.ejb.EJBException, the EJB container is required to throw javax.ejb.TransactionRolledbackLocalException, as mentioned in Table 15 on page 375 of the EJB 2.0 specification. Therefore, choice B is correct. Please refer to sections 18.2.2, 18.3.1, and 18.4.2.1 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: In which of the following cases will the EJB container discard a bean instance when an application exception is thrown from one of the bean's method?

Page 96 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Choices: ° ° ° ° ° ° A. When the method executes within the caller's transaction context B. When the bean uses BMT demarcation C. When the method executes within an unspecified transaction context D. When the bean executes in a transaction initiated by the container E. None of the above F. Only C and D

Correct choice: E Explanation: A bean instance is never discarded when an application exception is thrown from one of the bean's methods. Please refer to section 18 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
This section provided a look at the effects of various exceptions and errors encountered in EJB applications. We saw that application exceptions represent error conditions that the client expects and might be able to recover from, while system exceptions indicate conditions that are unrecoverable. We also explored the container and bean provider's responsibilities when dealing with different exceptions. It is important to be aware of the different exception types received by local and remote clients. Finally, we saw the details of the most common application and system exceptions in EJB.

Java certification success, Part 3: SCBCD

Page 97 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 14. Enterprise bean environment Environment entries
The enterprise bean's environment allows the bean behavior to be customized without the need to access or change the bean's source code. The container provides an implementation of the JNDI naming context that stores the enterprise bean environment. Environment entries are variables whose values are specified in the deployment descriptor and looked up by the bean using JNDI interfaces. Each enterprise bean defines its own set of environment entries. These values are read only at runtime. The value of an environment entry is of the Java type declared by the Bean Provider in the deployment descriptor. For example, the following elements in the deployment descriptor declare an environment entry areaCode of value 200 and type Integer:

<entity> ... <env-entry> <env-entry-name>areaCode</env-entry-name> <env-entry-type>java.lang.Integer</env-entry-type> <env-entry-value>200</env-entry-value> <env-entry> ... </entity>

An environment entry is scoped to the enterprise bean whose declaration contains the <env-entry> element. The environment entry values may be any of the following Java types: ° ° ° ° ° ° ° ° String Character Integer Boolean Double Byte Short Long

Page 98 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

Float

The JNDI lookup code for this environment entry is as follows:
InitialContext jndiContext=new InitialContext(); Integer lowerLimit =(Integer)jndiContext.lookup("java:comp/env/areaCode");

The Deployer must ensure that the values of all the environment entries declared by the bean are set to meaningful values. The Deployer uses the tools provided by the container to create the environment entries that are declared in the enterprise bean's deployment descriptor by the Bean Provider. He may set different values for the enterprise bean environment entries for each deployment/home of the bean.

EJB references
An enterprise bean can refer to the homes of other enterprise beans using "logical" names called EJB references. References to other beans can be local or remote. The Bean Provider declares the EJB references in the deployment descriptor and looks up the home interface of the referenced enterprise bean in the enterprise bean's environment using JNDI. The Deployer binds the EJB references to the real JNDI names of the enterprise bean homes in the target operational environment. Local EJB references are declared using the <ejb-local-ref> element and remote EJB references, using the <ejb-ref> element. The EJB specification recommends -- but does not require -- that all references to other enterprise beans be organized in the ejb sub-context of the bean's environment (that is, in the "java:comp/env/ejb" JNDI context). For example, the following elements in the deployment descriptor declare an EJB reference Emp within the subcontext ejb:
<entity> ... <ejb-ref> <ejb-ref-name>ejb/Emp</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home<EmpHome</home> <remote>EmpRemote</remote> </ejb-ref> ...

Java certification success, Part 3: SCBCD

Page 99 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

</entity>

A client can look up the home interface of the referenced bean using the following code:
Context initCtx = new InitialContext(); Object result = initCtx.lookup("java:comp/env/ejb/Emp"); EmpHome empHome = (EmpHome) javax.rmi.PortableRemoteObject.narrow(result, EmpHome.class);

The Application Assembler can use the <ejb-link> element in the deployment descriptor to link an EJB reference to a target enterprise bean. The value of the <ejb-link> element in the referencing enterprise bean element is the <ejb-name> of the target enterprise bean. The <ejb-link> element is a sub-element of the <ejb-ref> or <ejb-local-ref> element. The following example illustrates the use of the <ejb-link> element:
<entity> ... <ejb-ref> <ejb-ref-name>ejb/Emp</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>EmpHome</home> <remote>EmpRemote</remote> <ejb-link>EmployeeRecord</ejb-link> </ejb-ref> ... </entity>

In some other part of the same deployment descriptor, EmployeeRecord must be defined in the <ejb-name> element of the target bean as shown:
<session> <ejb-name>EmployeeRecord</ejb-name> ... </session>

The Deployer: ° Must ensure that all the declared EJB references are bound to the homes of enterprise beans that exist in the operational environment Must ensure that the target enterprise bean is type-compatible with the types declared for the EJB reference

°

Page 100 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

°

Must bind the enterprise bean reference to the home of the enterprise bean specified as the link's target, if an EJB reference declaration includes the <ejb-link> element

Resource manager connection factories
A resource manager connection factory is an object that is used to create connections to a resource manager like a database. The enterprise bean code can refer to resource factories using logical names called resource manager connection factory references. The Bean Provider declares the resource manager connection factory references in the deployment descriptor using the <resource-ref> element and looks up the resource manager connection factory object using JNDI. A resource manager connection factory reference is scoped to the enterprise bean whose declaration contains the <resource-ref> element, so there aren't any naming conflicts with other beans. The standard resource manager connection factory types are: ° javax.sql.DataSource resource manager connection factory type: For obtaining JDBC connections javax.jms.QueueConnectionFactory or the javax.jms.TopicConnectionFactory: For obtaining JMS connections javax.mail.Session resource manager connection factory type: For obtaining JavaMail connections java.net.URL resource manager connection factory type: For obtaining URL connections

°

°

°

The following example shows how we define a DataSource reference in the deployment descriptor:
<resource-ref> <res-ref-name>jdbc/OrderAppDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth<Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref>

The possible values for the <res-auth> element are Application and

Java certification success, Part 3: SCBCD

Page 101 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Container. Application indicates that the enterprise bean code performs resource manager sign-on programmatically. Container indicates that the container signs on to the resource manager using the principal mapping information configured by the Deployer. The <res-sharing-scope> element indicates whether connections to the resource manager obtained through the given resource manager connection factory reference can be shared or whether the connections are unshareable. Possible values are Shareable and Unshareable. The following code sample illustrates obtaining a JDBC connection using the reference declared above:
Context initCtx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource)initCtx.lookup("java:comp/env/jdbc/OrderAppDB"); java.sql.Connection con = ds.getConnection();

The Deployer is responsible for mapping the <res-ref-name> element provided by the Bean Provider to the actual JNDI name of the resource manager connection factory in the operational environment. If the value of the <res-auth> element is Container, the Deployer is responsible for configuring the sign-on information. The system administrator adds, removes, and configures resource managers in the EJB Server environment, and he is also in charge of giving them meaningful JNDI names.

Resource environment references
Resource Environment references are logical names that refer to administered objects associated with the resources. Right now, JMS destinations are the only administered objects available. The Bean Provider must declare all the references to administered objects associated with resources using the <resource-env-ref> elements of the deployment descriptor. A resource environment reference is scoped to the enterprise bean whose declaration contains the <resource-env-ref> element. The Deployer binds the resource environment references to administered objects in the target operational environment. The EJB specification recommends, but does not require, that all resource environment references be organized in the appropriate subcontext of the bean's environment for the resource type (for example, in the

Page 102 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

"java:comp/env/jms" JNDI context for JMS destinations). We can declare the JMS destination in the deployment descriptor, as shown below:
<resource-env-ref> <resource-env-ref-name> jms/ReservationQueue </resource-env-ref-name> <resource-env-ref-type> javax.jms.Queue </resource-env-ref-type> </resource-env-ref>

In the bean's business method, we can look up the object as illustrated below:
Context initCtx = new InitialContext(); Object result = initCtx.lookup("java:comp/env/jms/ReservationQueue"); javax.jms.Queue queue = (javax.jms.Queue)result;

Sample questions
Question 1: Which of the following are valid Java types that the <env-entry-type> deployment descriptor element can contain? Choices: ° ° ° ° ° A. java.lang.Integer B. int C. java.lang.Double D. double E. java.lang.Object

Correct choice: A and C Explanation: The only Java types that are valid values for the <env-entry-type> deployment descriptor element are: ° ° java.lang.Byte java.lang.Short

Java certification success, Part 3: SCBCD

Page 103 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° ° ° ° ° ° °

java.lang.Character java.lang.Integer java.lang.Long java.lang.Float java.lang.Double java.lang.Boolean java.lang.String

Therefore, choices A and C are correct, and choice E is incorrect. Choice B and D are incorrect because you cannot specify a primitive type as the type for an environment entry value. Please refer to section 20.2.1.2 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: Which of the following sub-elements of the <ejb-ref> element is optional when defining references to other enterprise beans? Choices: ° ° ° ° ° A. <ejb-ref-name> B. <ejb-ref-type> C. <home> D. <ejb-link> E. <remote>

Correct choice: D Explanation: The <ejb-ref> element is used for referencing an enterprise bean that is accessed through its remote home and remote interfaces. Its required child elements are: ° ° ° ° <ejb-ref-name> <ejb-ref-type> <remote> <home>

Page 104 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

<ejb-link> and <description> are the optional child elements. The <ejb-ref-name> element specifies the EJB reference name; its value is used in the enterprise bean code. The <ejb-ref-type> element specifies the expected type of the enterprise bean -- session or entity. The <home> and <remote> elements specify the expected Java types of the referenced bean's home and component interfaces. The application assembler uses the optional <ejb-link> element to link an EJB reference to a target enterprise bean. The value of the <ejb-link> element must match with one of the <ejb-name> values of the target enterprise bean. For more information, refer to section 20.3.1.2 of the EJB 2.0 specification (see Resources on page113 ).

Summary
One of the most special features of enterprise beans is the support for customizing the bean at deployment time without modifying the source code in any way. In the bean's unique environment, we learned how to configure different things like environment entries, resource manager connection factories, enterprise bean references, and resource environment references. Using these declared references, the Bean Provider looks up the different variables or objects using JNDI interfaces.

Java certification success, Part 3: SCBCD

Page 105 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Section 15. Security management Overview
Security management in EJB applications can be achieved in two ways: programmatically and declaratively. It is preferable to choose the declarative way because you can customize the security policies through the deployment descriptor without altering the source code of the bean. However, when instance-level authorization is required, you need to make use of programmatic security. A security role is a logical role that a given type of user must belong to in order to successfully use an application. Security roles are mapped to real world users and groups when the bean is deployed. Because you don't have to hard code specific user identities into the bean code, it makes enterprise beans more portable. You need to use security roles whether you are using declarative or programmatic authorization.

Programmatic security
To gain fine-grained control over security, which cannot be achieved through declarative authorization, you can use programmatic access control. To do so, we need to get the identity of the users who are invoking the bean methods. Accessing caller information The javax.ejb.EJBContext interface provides two methods that allow the Bean Provider to access security information about the caller of an enterprise bean. The Bean Provider can invoke these methods only in the enterprise bean's business methods for which the container has a meaningful client security context: ° java.security.Principal getCallerPrincipal();: Allows the enterprise bean methods to obtain the name of the current caller principal. After authentication, the security identity of the client is represented by a java.security.Principal object. boolean isCallerInRole(String roleName);: Tests whether the current caller has been assigned to the given security role.

°

The following example shows how to use these methods:

Page 106 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

private void modifyEmployee() { if (!ejbContext.isCallerInRole(("payroll")) { throw new SecurityException(...); } else { // perform secure tasks here } } private void checkUser() { Principal callerPrincipal = ejbContext.getCallerPrincipal(); String callerName = callerPrincipal.getName(); // use the name in a database query }

Declaration of security roles referred in the bean code The Bean Provider must declare each security role referenced in the code using the <security-role-ref> element:
<entity> <ejb-name>PayrollEJB</ejb-name> <ejb-class>com.abc.PayrollBean</ejb-class> <security-role-ref> <role-name>payroll</role-name> </security-role-ref> </entity>

A security role reference is scoped to the session or entity bean element whose declaration contains the <security-role-ref> element. Mapping the security roles The role references, which are names hard coded by the Bean Provider, need to be mapped to the actual security roles defined by the Application Assembler. This mapping is performed by the application assembler using the <role-link> element as shown below. The value of the <role-link> element must be the name of one of the security roles defined in a <security-role> element.
<security-role-ref> <role-name<payroll</role-name> <role-link>payroll-department</role-link> </security-role-ref>

The security roles are defined by the Application Assembler using the <security-role> element within the <assembly-descriptor> element,

Java certification success, Part 3: SCBCD

Page 107 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

as illustrated below:
<assembly-descriptor> <security-role> <role-name>payroll-department</role-name> </security-role> </assembly-descriptor>

Declarative security
The Application Assembler can restrict the access to bean methods to certain privileged roles by defining method permissions in the deployment descriptor. A method permission is a permission to invoke the specified method of the enterprise bean's home and component interfaces. In the following example, the permission to access the findByPrimaryKey() method of PayrollEJB has been granted to the security role payroll-department:
<method-permission> <role-name>payroll-department</role-name> <method> <ejb-name>PayrollEJB</ejb-name> <method-name>findByPrimaryKey</method-name> </method> </method-permission>

The wild card character * can be used in the <method-name> element to indicate all the methods. By specifying arguments using the <method-params> element, you can distinguish among different overloaded methods. We can differentiate among methods having the same name in the home or component interface by using the <method-intf> element -- values can be Remote, Home, Local, or LocalHome. These elements are illustrated below:
<method-permission> <role-name>payroll-department</role-name> <method> <ejb-name>PayrollBean</ejb-name> <method-intf>Local</method-intf> <method-name>myMethod</method-name> <method-params> <method-param>String</method-param> <method-params>

Page 108 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

</method> </method-permission>

The Application Assembler uses the <unchecked> element instead of a role name in the <method-permission> element to indicate that a method should not be checked for authorization. If the method permission relation specifies both the <unchecked> element for a given method and one or more security roles, the method should not be checked for authorization. The Application Assembler can use the <exclude-list> element to indicate the set of methods that should not be called. If a given method is specified both in the <exclude-list> element and in the method permission relation, the enterprise bean's security should be configured such that no access is permitted to the method.

Propagating security identity
When you call a method on an EJB, the container automatically propagates the caller's security context from method to method, throughout the application. The Application Assembler uses the <security-identity> element to specify whether the caller's security identity should be used for the execution of the bean methods or whether some other identity must be used. The value of the <security-identity> element is either <use-caller-identity> (the default) or <run-as>. You should specify the value as <run-as> when you want the bean to act as someone other than the calling client. The run-as identity is designated by one of the security roles defined by the application assembler in the deployment descriptor, as shown in the following example:
<session> <ejb-name>EmployeeInfo</ejb-name> <security-identity> <run-as> <role-name>admin</role-name> </run-as> </security-identity> </session>

The run-as identity establishes the identity the enterprise bean will use when it makes calls to other enterprise beans; it does not affect the identities of its callers.

Java certification success, Part 3: SCBCD

Page 109 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

The <use-caller-identity> value cannot be specified for MDB, because they don't have a calling client.

Responsibilities of the Deployer
The mapping of the security roles to actual users or groups in the operating environment is done by the Deployer in a vendor-specific manner. Assigning the security domain and principal realm to an enterprise bean application is also the Deployer's job. The Deployer must ensure that the assembled application is secure after it has been deployed in the target operational environment. He also performs any tasks that have been left unfinished by the Application Assembler.

Sample questions
Question 1: Which of the following statements about security management of enterprise beans are correct? Choices: ° ° ° ° A. The run-as identity applies to the enterprise bean as a whole. B. The run-as identity can be specified for any method. C. The run-as identity is usually specified using the <runas> element. D. The run-as identity does not affect the identity of the bean's callers.

Correct choice: A and D Explanation: Choice A is correct because the run-as identity always applies to the enterprise bean as a whole. It is not possible to assign a run-as identity on a per-method basis. Therefore, choice B is incorrect.

Page 110 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Choice C is incorrect because the deployment descriptor element used for specifying the run-as identity is <run-as>. Choice D is correct because the run-as identity establishes the identity the enterprise bean will use when it makes calls. Please refer to section 21.3.4 of the EJB 2.0 specification for further details (see Resources on page113 ). Question 2: Read the following code (assume that all references have been properly initialized):
public String getAdminPassword() { if (ejbContext.isCallerInRole("admin")) { return adminPassword; } else { return null; } }

In which deployment descriptor element must the admin role be defined? Choices: ° ° ° ° ° A. <security> B. <security-role> C. <security-role-ref> D. <security-role-reference> E. None of the above

Correct choice: C Explanation: If some code can only be accessed based on the caller's role, the Bean Provider declares the role used in the code by utilizing the <security-role-ref> deployment descriptor element. Therefore, choice C is correct, while choice E is incorrect. Choices A and D are incorrect because no such elements exist.

Java certification success, Part 3: SCBCD

Page 111 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

Choice B is incorrect because the application assembler is responsible for defining the <security-role> elements and for linking them to the <security-role-ref> elements defined by the Bean Provider. Note that another way to achieve the same result would be to assign the admin security role to the getAdminPassword() method in a <method-permission> element. Please refer to section 21.2.5.3 of the EJB 2.0 specification for further details (see Resources on page113 ).

Summary
In this section, you learned about programmatic and declarative security management techniques. Different processes are involved, such as defining security roles, security role references, and method permissions, which are handled by the various EJB roles like Bean Provider, Application Assembler, and Deployer. We also discussed the two programmatic security control methods that are invoked on the context of the enterprise bean. Finally, we explored the <security-identity> element that allows us to specify alternate caller identities for the execution of bean methods.

Page 112 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Section 16. Wrap-up and resources Summing up the tutorial
Preparing for a certification exam is quite different from learning the technology. Even if you are an experienced professional in the relevant field, your success in the exam is assured only if you follow a focused learning approach based on the exam objectives. We hope that this tutorial helped to familiarize you with the exam objectives and the kind of questions asked. To gain a deep understanding of the concepts, it is also necessary to get sufficient hands-on experience in all the areas covered by the exam. We recommend that you try out the code fragments and deployment descriptor customization examples provided in the tutorial. The SCBCD certification tests your competence in server-side component development using the EJB technology. Success in this exam will definitely boost your confidence level and give you a competitive edge in your career. We hope that this tutorial has been effective in providing you a clear insight into the exam objectives and preparing you for the certification. Enjoy your studies and good luck with the exam!

Resources
° Download the EJB 2.0 Specifications (http://java.sun.com/products/ejb/docs.html#specs) . Get a good grounding in EJB technology from these tutorials: ° Getting started with EJB technology (developerWorks, April 2003) ° The four-part series, Introduction to container-managed persistence and relationships, Part 1, Part 2, Part 3, and Part 4 (developerWorks, March 2002 -July 2002) ° EJB 2.0 CMP Tutorial ° Writing Enterprise Applications The following resources will help elevate your SCBCD competency: ° Head First EJB by Kathy Sierra and Bert Bates (O'Reilly 2003) ° Enterprise Java Beans -- 3rd Edition by Richard Monson-Haefel (O'Reilly

°

°

Java certification success, Part 3: SCBCD

Page 113 of 115

ibm.com/developerWorks

Presented by developerWorks, your source for great tutorials

° °

2001) Mastering Enterprise JavaBeans -- 2nd Edition by Ed Roman, Scott Ambler, Tyler Jewell, and Floyd Marinescu (Wiley 2001) An introductory article on SCBCD certification by the authors of this tutorial.

°

Practice and assess your knowledge level using the Whizlabs SCBCD Exam Simulator (http://www.whizlabs.com/products/scbcd/scbcd.html) . Get effective guidance and reinforce your concepts for the exam by enrolling in Whizlabs SCBCD Instructor-Led Online Training (http://www.whizlabs.com/scbcd/training.html) . Enhance your knowledge by participating in the JavaRanch SCBCD discussion forum. Here is a nice collection (http://www.valoxo.ch/jr/SCBCD_Links.html) of additional resources that you must explore. Browse a wide range of excellent titles at the developerWorks Developer Bookstore (http://devworks.krcinfo.com/) . Find more resources related to the technologies discussed here on the developerWorks Java technology zone (http://www.ibm.com/developerworks/java/) . Find out how you can become an IBM Certified Developer (http://www-1.ibm.com/certify/certs/adcdxmlrt.shtml) .

°

°

°

°

°

°

Your feedback
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG heading graphics, and two PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. (It also saves our production team a great deal of time and effort.)

Page 114 of 115

Java certification success, Part 3: SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

For more information about the Toot-O-Matic, visit www-106.ibm.com/developerworks/xml/library/x-toot/ .

Java certification success, Part 3: SCBCD

Page 115 of 115

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->