java certification success, part 3: scbcd€¦ ·  · 2010-01-15execution of multiple instances....

107
Java certification success, Part 3: SCBCD Skill Level: Intermediate Seema Manivannan ([email protected]) Corporate Trainer Whizlabs Pradeep Chopra ([email protected]) Cofounder of Whizlabs Software Whizlabs 09 Sep 2004 This tutorial is designed to aid EJB professionals in preparing for the Sun Certified Business Component Developer (SCBCD) for the Java 2 Platform, Enterprise Edition 1.3 Exam. Certification experts Seema Manivannan and Pradeep Chopra of Whizlabs walk you through the core concepts that are tested in the SCBCD exam, offering guidance and sample questions to test your knowledge along the way. Note: This tutorial is not intended to teach basic EJB concepts; it focuses only on what you need to know to be successful in the exam. 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). Java certification success, Part 3: SCBCD © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 107

Upload: phungkiet

Post on 30-May-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

Java certification success, Part 3: SCBCDSkill Level: Intermediate

Seema Manivannan ([email protected])Corporate TrainerWhizlabs

Pradeep Chopra ([email protected])Cofounder of Whizlabs SoftwareWhizlabs

09 Sep 2004

This tutorial is designed to aid EJB professionals in preparing for the Sun CertifiedBusiness Component Developer (SCBCD) for the Java 2 Platform, Enterprise Edition1.3 Exam. Certification experts Seema Manivannan and Pradeep Chopra of Whizlabswalk you through the core concepts that are tested in the SCBCD exam, offeringguidance and sample questions to test your knowledge along the way. Note: Thistutorial is not intended to teach basic EJB concepts; it focuses only on what you needto know to be successful in the exam.

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 developserver-side components that encapsulate the business logic of an application.Passing the exam demonstrates an expert level of understanding of the EnterpriseJavaBeans (EJB) 2.0 architecture, technology features, and application developmentlifecycle.

The exam was launched worldwide on August 25, 2003. The SCBCD certificationrequires you to be a Sun Certified Programmer for the Java platform (any edition).

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 107

Should I take this tutorial?

The exam is intended for EJB professionals who have at least some experiencedeveloping and deploying server-side applications using EJB 2.0 components. Thistutorial comprehensively covers the core concepts that are tested in the SCBCDexam; however, it is not intended to serve as an introduction to EJB technology. Itfocuses precisely on what you need to know to be successful in the exam.

The 14 exam objectives mainly deal with EJB technology basics, lifecycle andbehavior of different bean types, how the clients interact with the beans,container-managed persistence (CMP), transactions, and security management. Thetutorial is organized according to the exam objectives, with each section dedicated toa corresponding exam objective. In addition, we've provided example code wherevernecessary, and at the end of each section, we have provided sample examquestions, which test the concepts discussed under that objective. Each questionincludes detailed explanations about why a choice is correct or incorrect.

In every section, you must devote special attention to the responsibilities of differentEJB roles, such as Bean Provider, Application Assembler, and Deployer. For theexam, you need to know which role has the primary responsibility for different tasksin the EJB application lifecycle.

Section 2. EJB overview

Introduction

Enterprise JavaBeans (EJB) architecture is a server-side distributed componentmodel, which follows the "Write Once, Run Anywhere" philosophy of the Javaplatform. EJB applications can be written once and then deployed on anyEJB-compliant server without any source code changes or recompilation. Theruntime behavior of the enterprise bean can be customized through the deploymentdescriptor itself.

Enterprise beans typically contain the business logic of enterprise applications. TheEJB container provides services, such as security checks, resource pooling,networking, thread safety, transactions, persistence, and lifecycle management, thusallowing the developer to concentrate entirely on the business logic.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 2 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Types of enterprise beans

The three types of enterprise beans are session beans, entity beans, andmessage-driven beans (MDBs).

Session beans represent a process executing on behalf of a single client. Eventhough it does not directly represent shared data, it can access or update data in adatabase. Session beans can be stateful or stateless. A stateful session beanretains the conversational state of the client across multiple method calls. Statelesssession 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 allowshared access from multiple users. The entity, its primary key, and remote referencecan survive the crash of the EJB container.

Message-driven beans (MDBs) are asynchronously invoked when a clientmessage arrives. Clients never call them directly, so they do not have any home orcomponent interfaces.

EJB 2.0

Guaranteed features

EJB 2.0 technology has simplified the development and deployment of J2EEapplications 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 anapplication client user interface.

• Container-managed persistence (CMP) for entity beansContainer generates the database access code, thus resulting in portableapplications.

• Local component and home interfaces for session and entity beansProvides a local client view and support for efficient, lightweight access toenterprise beans from local clients.

• Home business methods for entity beans

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 107

Allows you to define business methods in the home interface of entitybeans.

• EJB Query Language (EJB-QL) for entity bean finder and selectmethodsProvides a portable, vendor-neutral way to define queries for finder andselect methods.

• Run-as security identity functionalityAllows you to specify a different principal, other than the calling client, forthe execution of the bean's methods.

• Network interoperability among EJB serversAllows EJB applications deployed on servers from different vendors tointeroperate using the RMI-IIOP protocol.

Supported APIs

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

• 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 youbuild portable EJB components:

• You must not use read/write static fields. Using read-only (final) staticfields is allowed.

• You must not use thread synchronization primitives to synchronize

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 4 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

execution of multiple instances.

• You must not attempt the use of the AWT functionality to outputinformation to a display, or to input information from a keyboard.

• You must not attempt the use of the java.io package to access filesand directories in the file system.

• You must not attempt to listen on a socket, accept connections on asocket, or use a socket for multicast.

• A bean may act as a network client (that is, it may make use of thejava.net.Socket class), but it may not act as a network server, andthus, it must not use the java.net.ServerSocket class to acceptremote connections.

• You must not attempt to query a class to obtain information about thedeclared members that are not otherwise accessible to the enterprisebean because of the security rules of the Java language.

• You must not attempt to use the Reflection API to access information thatthe security rules of the Java programming language make unavailable.

• You must not attempt to create a class loader; obtain the current classloader; set the context class loader; set security manager; create a newsecurity manager; stop the JVM; or change the input, output, and errorstreams.

• 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 aparticular code source.

• You must not attempt to load a native library.

• You must not attempt to gain access to packages and classes that theusual rules of the Java programming language make unavailable to theenterprise bean.

• You must not attempt to define a class in a package.

• You must not attempt to access or modify the security configurationobjects (Policy, Security, Provider, Signer, and Identity).

• You must not attempt to use the subclass and object substitution features

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 107

of the Java Serialization protocol.

• You must not attempt to pass the this reference of the bean as anargument or method result. The enterprise bean must pass the result ofSessionContext.getEJBObject(),SessionContext.getEJBLocalObject(),EntityContext.getEJBObject(), orEntityContext.getEJBLocalObject() instead.

EJB roles

The EJB specification defines six distinct roles in the application developmentlifecycle:

• 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 handlemore than one role:

Enterprise Bean ProviderDesigns and develops the EJB components. The Bean Provider codes theJava classes that implement the enterprise bean's business methods, thebean's home, and component interfaces. The deliverables are ejb-jar files (thatinclude one or more beans and an XML deployment descriptor).

Application AssemblerCombines multiple enterprise beans with other types of application components(for instance, JSP components) to compose an application. The ApplicationAssembler delivers one or more ejb-jar files that contain the enterprise beansalong with their application assembly instructions.

DeployerTakes one or more ejb-jar files produced by a Bean Provider or ApplicationAssembler and deploys them in a specific EJB container. The Deployerdelivers enterprise beans that have been customized for the target operational

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 6 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

environment. To perform their role, the Deployers use tools provided by theEJB container.

EJB Container ProviderGives runtime support for the deployed enterprise bean instances. TheContainer Provider also delivers the deployment tools necessary for thedeployment of enterprise beans and tools that allow the System Administratorto monitor and manage the container and the beans.

EJB Server ProviderA specialist in the area of distributed objects, transactions, and otherlower-level system-level services. A typical EJB Server Provider is an OSvendor, middleware vendor, or database vendor. The current EJB architectureassumes that the EJB Server Provider and the EJB Container Provider rolesare the same vendor.

System AdministratorResponsible for the configuration and administration of the enterprise'scomputing and networking infrastructure that includes the EJB server andcontainer. It also oversees the well being of the deployed enterprise beanapplications 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 ofeach 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 nameejb-jar.xml in the META-INF folder. The ejb-jar file must also contain, either byinclusion or by reference, the class files for all the classes and interfaces that eachenterprise bean class and the home and component interfaces depend upon, exceptJ2EE and J2SE classes.

The ejb-jar file is not required to contain the manifest file. The stubs for remoteinterfaces and classes implementing the component, home interfaces are generatedby the container and hence are not included in the ejb-jar file.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 107

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

Correct choice:

D

Explanation:

The ejb-jar file is the standard format for packaging enterprise beans and assembledapplications. It contains the XML deployment descriptor, the enterprise beanclasses, the enterprise bean remote and home interfaces, and the primary key class(only for entity beans). The ejb-jar should also contain the superclasses andsuperinterfaces of the above classes. It should also include the dependent classesand the classes and interfaces used as method parameters, return types, andexceptions. 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).

Question 2:

Which of the following are not allowed in enterprise beans according to the EJB 2.0programming restrictions?

Choices:

• A. Extending from a class

• B. Creating client sockets

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 8 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• 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 theenterprise bean is portable and can be deployed in all EJB 2.0 containers. Anenterprise bean must not use read/write static fields, however static fields areallowed if they are made read-only by declaring them with the final keyword. Thebean must not attempt to load a native library; this restriction is to avoid securityholes. The enterprise bean must not manage threads or thread groups becausethese functions are reserved for the EJB container.

Choice A is incorrect because Java inheritance is allowed for enterprise beanclasses. Choice B is incorrect because the EJB architecture allows an enterprisebean instance to be a network client. However, it does not allow it to be a networkserver.

For a complete list of the EJB 2.0 programming restrictions, please refer to section24.1.2 of the EJB 2.0 specification (see Resources).

Summary

This section provided an overview of the EJB architecture and the different types ofenterprise beans. We discussed which features and APIs are guaranteed to besupported by the EJB 2.0 specification, and you now know the programmingrestrictions on EJB business methods to ensure that the bean is portable and can bedeployed in any compliant EJB 2.0 container. The responsibilities of the differentroles involved in the EJB development lifecycle are spread over the remainingobjectives. In this objective, we have simply provided an overall picture of theresponsibilities of each role.

Section 3. Client view of a session bean

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 107

Local and remote clients

A session bean can use its component interface to expose its business methods toclients. The Java object that implements the component interface is called the EJBObject of the bean. To invoke a business method on a session bean, the clientneeds to get a reference to the bean's EJB Object. The client obtains a reference tothe EJB Object by calling a method on the home object of the bean. The homeobject 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, thelocal component and home interfaces provide the client view. The local client view isnot location-independent. The arguments and results of the methods of the localinterface and local home interface are passed by reference.

A remote client of a session bean can be another enterprise bean deployed in thesame or different container; or it can be an arbitrary Java program, such as anapplication, applet, or servlet. It can even be a non-Java program, such as a CORBAclient. Here the remote component and home interfaces provide the client view. Theremote client view of a session bean is location-independent. The arguments andresults of the methods of the remote interface and remote home interface arepassed by value.

Even though it is possible for a session bean to have a local view and a remoteview, 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 andDirectory Interface (JNDI). The InitialContext class is the starting context forperforming JNDI naming operations. The lookup method takes the bean's JNDIname as the argument:

Context initialContext = newInitialContext();

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

When looking up the remote home object, thePortableRemoteObject.narrow() method must be used on the object returned

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 10 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

from the JNDI lookup, rather than using simple Java language casts. This method isrequired because the remote home stub, which is obtained from the JNDI lookup, isRMI-IIOP compatible and needs to be converted into a Java object that actuallyimplements 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 returnedis not a stub:

Context initialContext = newInitialContext();

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 objectThe home interface of a stateful session bean defines one or morecreate<METHOD>(...) methods to create a session object. The return type of acreate<METHOD>(...) method is the session bean's remote componentinterface:

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)throws RemoteException, CreateException;

}

The home interface of a stateless session bean defines only one create method,

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 107

which does not take any arguments.

Removing a session objectThe 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 theHandle as the argument. As session beans do not have primary keys, invoking theremove(Object primaryKey) method results injavax.ejb.RemoveException. For example:

MyRemote bean1=myHome.create();

Handle handle=bean1.getHandle();

// Call the bean business methods here.myHome.remove(handle);

Getting the EJBMetaDataThe EJBMetaData interface allows the client to obtain class information about theenterprise bean. This information is usually required by tools. ThegetEJBMetaData() method of the EJBHome interface returns an object thatimplements this interface:

public EJBMetaData getEJBMetaData()

Obtaining a home handleThe home handle is a serializable object that can be used at a later time to re-obtaina 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()

Local home interface

The local home interface extends the javax.ejb.EJBLocalHome interface andallows a client to create a new session object.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 12 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

A local client can create a session object by invoking any one of thecreate<METHOD> (...) methods, defined in the local home interface.

The only method defined in EJBLocalHome is voidremove(java.lang.Object primaryKey).

This method cannot be invoked by a client because session beans do not haveprimary keys. As a consequence, local clients cannot remove a session bean bycalling any methods on the home interface of the session bean.

Local clients do not need an EJBMetaData interface because they can usereflection to extract bean information. Also, handles are not required for local clientsbecause there aren't any stubs.

Component interface

The component interface exposes the business methods of the session object toclients. The EJB Object, which implements this interface, delegates invocation of abusiness 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.EJBLocalObjectinterface. The methods inherited from the javax.ejb.EJBLocalObject interfaceare:

• EJBLocalHome getEJBLocalHome()

• java.lang.Object getPrimaryKey()

• boolean isIdentical(EJBLocalObject obj)

• void remove()

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 107

Invoking the getPrimaryKey() method for a session object raises aRemoteException in the case of an EJBObject and an EJBException for theEJBLocalObject interface.

Getting the home object referenceIf the reference to the EJB Object is available, we can get a reference to the bean'shome object using the getEJBHome() method for remote clients andgetEJBLocalHome() for local clients. This method of obtaining the home objectreference is more efficient than performing a JNDI lookup to locate the home.

Getting the handleA 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 canserialize the Handle object at any time and deserialize it later to obtain a referenceto the original EJB object. The EJBObject.getHandle() method returns aHandle object. Because local clients do not need handles, the EJBLocalObjectinterface does not define a similar method.

Removing the beanThe remove method in the EJBObject and EJBLocalObject interfaces can beused to remove the EJB Object. It tells the container to free up any resources heldfor the bean.

Comparing session objectsThe isIdentical() method defined in EJBObject and EJBLocalObject isused to compare two EJB Object references.

Stateless session beans created from the same home have the same identityassigned 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 identitybecause they hold the client conversational state. So two stateful session beaninstances created from the same home are not considered identical. For example:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 14 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 theresponsibility of the (remote or local) home interface.

Choice B is correct because the component interface provides a method calledremove() that allows the client to remove the associated session bean.

Choice C is correct because the local and remote component interfaces providemethods called getEJBLocalHome() and getEJBHome() that return the local andremote home interfaces of the session bean, respectively.

Choice D is incorrect because only the remote component interface provides theability to get a handle for later use.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 107

Choice E is incorrect because session beans do not make their identity available toclients. As a result, when the getPrimaryKey() method is invoked on the localand remote component interfaces, a javax.ejb.EJBException andjava.rmi.RemoteException will be thrown respectively to the client.

Please refer to section 6.5 of the EJB 2.0 specification for further details (seeResources).

Question 2:

What kind of argument must be passed to the isIdentical() method to testwhether two remote component interface references are referring to the samesession 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 wantto test remote component interfaces, we consider the former one, which defines theisIdentical() method as follows:

public boolean isIdentical(EJBObject other);

Please refer to section 6.9 of the EJB 2.0 specification for further details (seeResources).

Summary

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 16 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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

Section 4. Session bean component contract

Overview of session beans

Session beans are responsible for managing client processes. They are relativelyshort-lived and do not survive server crashes. Though they do not represent shareddata in the database, they may access or update such data.

Stateful session beans retain the conversational state of the client, while Statelesssession beans are dedicated to a client only for the duration of the method call.Stateless session beans can have instance variables, but they cannot preserveclient data across multiple method invocations. All instances of a particular type ofstateless session bean are equivalent, so the container may choose any availableinstance to serve a client method call. Two successive client calls to a statelesssession bean may be served by two different instances of that session bean.

All session beans must implement the javax.ejb.SessionBean interface. Thecontainer uses the SessionBean() methods to notify lifecycle events to theenterprise bean instances. The methods defined in this interface are:

• void ejbActivate()

• void ejbPassivate()

• void ejbRemove()

• void setSessionContext(SessionContext ctx)

The setSessionContext() method is invoked on a session bean instance afterits construction. The SessionContext reference may be stored in an instance fieldof the session bean for future use.

The ejbPassivate() notification signals the intent of the container to passivate

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 107

the instance.

The ejbActivate() notification signals that the instance has just beenreactivated.

The ejbRemove() notification signals that the instance is in the process of beingremoved by the container.

The ejbPassivate() and ejbActivate() methods are invoked only in the life ofstateful beans and not for stateless session beans. The reason is that statelesssession beans do not need to persist the client state. All the instances of a particulartype of a stateless session bean are equivalent, and the same instance may bereused to serve multiple clients. Even though stateless beans are never passivated,we need to define the ejbActivate() and ejbPassivate() callback methods inthe bean class because the class implements the SessionBean interface. Forexample:

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 theejbCreate<METHOD>() method whose signature matches that of the create<METHOD>() method. Each stateful session bean class must have at least oneejbCreate<METHOD>() method. The stateless session bean class can have onlyone 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;

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 18 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

}

Passivation of a stateful session bean

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

Responsibilities of the bean providerAll open resources, such as JDBC connections, must be closed in theejbPassivate() method and reopened in ejbActivate().

After ejbPassivate(), the non-transient fields of the bean may consist of onlyprimitive 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 JNDIcontext)

• A reference to the UserTransaction interface

• A reference to a resource manager connection factory

• An object that is not directly serializable, but becomes serializable byreplacing the references to the special types mentioned above withserializable objects

The Bean Provider should not store in a transient field a reference to any of thefollowing objects:

• SessionContext object

• Environment JNDI naming context and any of its subcontexts

• Home and component interfaces

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 107

• UserTransaction interface

The content of transient fields may be lost between the ejbPassivate andejbActivate notifications.

Responsibilities of the containerThe container performs Java serialization (or its equivalent) to passivate the beaninstance. A stateful session bean may not be passivated while it is participating in atransaction. The container must be able to properly save and restore the specialtypes mentioned in the previous section, even though they are not serializable. Asession bean instance may be destroyed if the instance does not meet thepassivation requirements.

SessionContext interface

The SessionContext interface represents the bean's context maintained by thecontainer. A reference to the SessionContext object is passed to the bean whenthe 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.Principalthat identifies the invoker of the bean instance's EJB Object.

• isCallerInRole(): Tests whether the session bean instance's callerhas a particular role.

• setRollbackOnly(): Allows the instance to mark the currenttransaction for a rollback. It is only for session beans withcontainer-managed transaction (CMT) demarcation.

• getRollbackOnly(): Allows the instance to test whether the currenttransaction has been marked for roll back. It is only for session beans withCMT demarcation.

• getUserTransaction(): Returns ajavax.transaction.UserTransaction reference for use by session

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 20 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

beans with bean-managed transaction (BMT) demarcation.

SessionSynchronization interface

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

The javax.ejb.SessionSynchronization interface declares the followingmethods:

• afterBegin(): Notifies the bean instance that a new transaction hasstarted.

• beforeCompletion(): Notifies the instance that a transaction is aboutto be committed. This method is not invoked if the transaction is markedfor rollback.

• afterCompletion(boolean flag): Notifies the instance that thecurrent transaction has completed. The flag is true if the transaction hasbeen committed and false if it has been rolled back.

BMT beans must not implement this interface, because they are themselvesresponsible for demarcating transactions. Stateless session beans are not allowedto maintain transactions across multiple methods, so they must not implement thisinterface.

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 thesession bean provides a remote client view

• Session bean's local interface and local home interface, if the sessionbean provides a local client view

The classes must follow certain programming guidelines as specified below.

Session bean class

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 107

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

• It may (but is not required to) implement the session bean's componentinterface.

• It must implement the business methods and the ejbCreate()methods.

• If the class is a stateful session bean, it may optionally implementjavax.ejb.SessionSynchronization.

• The session bean class may have superclasses and/or superinterfaces.

ejbCreate<METHOD>() methods

• The session bean class must define one or moreejbCreate<METHOD>(...) methods in the case of stateful sessionbeans, and no more than one no-argument ejbCreate() method in thecase 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 acreate<METHOD>(...) method corresponding to theejbCreate(...) method on the session bean's remote home interface.

• The throws clause of the method may define arbitrary applicationexceptions, 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 forRMI/IIOP if the method corresponds to a business method on the session

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 22 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

bean's remote interface.

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

Component interface

• The remote interface must extend the EJBObject interface and the localinterface must extend the EJBLocalObject interface.

• The methods defined in the remote interface must follow the rules forRMI/IIOP.

• The interface is allowed to have superinterfaces.

• For each method defined in the interface, there must be a matchingmethod in the session bean's class.

• All the exceptions defined in the throws clause of the matching methodof the session bean class must be defined in the throws clause of themethod of the interface.

• The remote interface methods must not expose local home or componentinterface types.

• The remote interface methods must definejava.rmi.RemoteException in the throws clause, while the localinterface methods must not.

Home interface

• The remote home interface must extend the EJBHome interface and thelocal 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 mustmatch one of the ejbCreate<METHOD> methods defined in the sessionbean class, the return type is different.

• The methods for a stateless session bean must be named create() andejbCreate().

• The return type for a create<METHOD>() method must be the session

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 107

bean's component interface type.

• The remote home interface methods must definejava.rmi.RemoteException in the throws clause, while the localhome interface methods must not.

• The throws clause of the create() methods must includejavax.ejb.CreateException.

Responsibilities of the container

The deployment tools provided by the container are responsible for the generation ofthe 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 remoteinterfaces

• A class that implements the EJBMetaData interface and providesmetadata 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 anotherrequest, the container may throw java.rmi.RemoteException to the secondrequest if the client is a remote client, or javax.ejb.EJBException if the client isa local client.

Sample questions

Question 1:

Which of the following method declarations for a session bean class are valid?

Choices:

• A. public void ejbCreate(String name) throws

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 24 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 mustbe prefixed with ejbCreate. Moreover, the method declaration must be public, itmust neither contain the final nor static modifiers, its arguments must be legalRMI-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 clausemust contain the javax.ejb.CreateException as well as arbitrary applicationexceptions. Thus, only choices A and B are correct.

Moreover, each ejbCreate<METHOD>() method must correspond to acreate()<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 nottake 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 (seeResources).

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 typejavax.ejb.EJBContext

• B. An unsetSessionContext() method

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 107

• C. Three methods that have the same signature as methods defined inthe 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 doesdefine a setSessionContext() method, the argument is of typejavax.ejb.SessionContext and not javax.ejb.EJBContext.

Choice B is incorrect because the javax.ejb.SessionBean interface does notdeclare any method called unsetSessionContext(). It is worth noting that onlythe javax.ejb.EntityBean interface defines a method for unsetting the contextof the bean.

Choice C is correct because both the javax.ejb.SessionBean and thejavax.ejb.EntityBean interfaces define three methods that have the samesignature:

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

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 providedthrough the local or remote home interface.

Please refer to section 7.5.1 of the EJB 2.0 specification for further details (seeResources).

Summary

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 26 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

This section briefly covered the differences between stateful and stateless sessionbeans. We identified the methods defined in the SessionBean andSessionContext interfaces. The significance of the SessionSynchronizationinterface, which can be optionally implemented by stateful session beans, was alsodiscussed. Finally, we concentrated on the responsibilities of the Bean Provider andthe container with regard to session beans.

Section 5. Session bean lifecycle

Stateful session beans

The lifetime of a stateful session bean instance is controlled by the client. The beancontains conversational state that must be retained across methods andtransactions.

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 invokesthe setSessionContext() method, passing a SessionContext instance. Thebean is assigned to its EJB Object. The container invokes the ejbCreate()method matching the create() method invoked by the client. The reference to theEJB 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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 107

resources. When the bean is about to be passivated, the ejbPassivate() methodis invoked. A session bean cannot be passivated while it is in a transaction. If aclient invokes a session object whose session bean instance has been passivated,the container will activate the instance. To this end, the container invokesejbActivate() on the bean after successfully restoring it from the Passive state.

If the client invokes the remove() method on the bean, the container invokesejbRemove() on the bean and moves out of the Ready state into theDoes-not-exist state. This can also happen when a bean times out in the Readystate. Note that the bean cannot time out while in a transaction.

Under certain conditions, the ejbRemove() method might not be invoked on asession 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 muchsimpler as compared to that of a stateful session bean. The container can instantiatethe stateless session bean at any time, it is not related to the client's invocation ofthe 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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 28 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

ejbCreate(), and the bean is ready to serve client requests. When a clientinvokes 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 containerselects one of its method-ready instances and ties it to the client's EJB Object, onlywhen the client calls a business method.

After serving the client, the bean is disassociated from the EJB Object and returns tothe Ready state. When the container no longer needs the instance, the containerinvokes ejbRemove() on it.

Operations allowed in the methods of a stateful session bean

• getEJBObject() and getEJBLocalObject() of SessionContextCan be invoked from all the methods except setSessionContext()and the constructor because there is no session object identity availablein those methods.

• getCallerPrincipal() and isCallerInRole() ofSessionContextCan be invoked from all the methods except setSessionContext()and the constructor because there is no client security context available inthose methods.

• getRollbackOnly() and setRollbackOnly() of SessionContextCan be invoked only from the afterBegin() andbeforeCompletion() business methods because there is nomeaningful transaction context available in other methods. Moreover, onlybeans with CMT demarcation can invoke these methods.

• getUserTransaction() of SessionContext methods ofUserTransactionCan be invoked from the ejbCreate(), ejbRemove(),ejbActivate(), and ejbPassivate() business methods of beanswith BMT demarcation.

• Accessing resource managers and enterprise beansNot allowed in the session bean methods for which the container does nothave a meaningful transaction context or client security context. So theycan be called in every method except setSessionContext() andafterCompletion().

• getEJBHome() and getEJBLocalHome() of SessionContext, JNDIaccess to java:comp/envAllowed in all methods except the constructor.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 107

Operations allowed in the methods of a stateless session bean

• getEJBObject() and getEJBLocalObject() of SessionContextCan be invoked from all the methods except setSessionContext()and the constructor because there is no session object identity availablein those methods.

• getCallerPrincipal() and isCallerInRole() ofSessionContextCan be invoked from business methods only because there is no clientsecurity context available in other methods.

• getRollbackOnly() and setRollbackOnly() of SessionContextCan be invoked only from business methods because there is nomeaningful transaction context available in other methods. Only beanswith CMT demarcation can invoke these methods.

• getUserTransaction() of SessionContextCan be invoked from the ejbCreate() and ejbRemove() businessmethods of beans with BMT demarcation.

• Methods of UserTransactionCan be invoked only from business methods of beans with BMTdemarcation.

• Accessing resource managers and enterprise beansNot allowed in the session bean methods for which the container does nothave a meaningful transaction context or client security context. So theycan be called only from business methods.

• getEJBHome() and getEJBLocalHome() of SessionContext, JNDIaccess to java:comp/envAllowed 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 theDoes-not-exist state?

Choices:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 30 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• 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 sufficientsecurity 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-existstate. When either the bean is in the Ready state and a timeout occurs (choice A) orthe client invokes remove() on the component interface of the bean (choice E), theEJB container invokes ejbRemove() on the bean instance, which makes it transitto 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 themethod-ready state to the Passive state.

Choice C is incorrect because it is the container's job to invoke ejbRemove() onthe 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 hasbeen denied by the EJB container, the EJB container throws ajava.rmi.RemoteException to a remote client and ajavax.ejb.EJBException to a local client. These are considered to be systemexceptions. When a system exception is thrown from any method of the beanregardless 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).

Question 2:

Which of the following operations are allowed in the afterCompletion() methodof a session bean that defines a remote client view?

Choices:

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 107

• A. Invoke getPrimaryKey() on the SessionContext object

• 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 beanwith a CMT demarcation because it defines the afterCompletion() method ofthe javax.ejb.SessionSynchronization interface. BMT session beans andstateless session beans are not allowed to implement that interface.

Choice A is incorrect because session beans do not publicly release their primarykey, which is kept internal to the container.

Choice B is incorrect because a session bean must not access another enterprisebean while executing the afterCompletion() callback.

Choice C is incorrect because the question states that the session bean defines aremote client view. As a result, it is not allowed to invoke getEJBLocalHome() onthe SessionContext object. An IllegalStateException is thrown by thecontainer if it does.

Choice D is correct because it is perfectly acceptable for the session bean to invokethe getEJBObject() method on the SessionContext object.

Choice E is correct because the bean is allowed to perform JNDI lookups from anyinstance 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 (seeResources).

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.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 32 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Because stateless session beans do not maintain client state, their lifetime is notcontrolled by the client, which makes the event flow different from that of statefulbeans. We also reviewed the operations that are allowed to be performed from thevarious bean methods.

Section 6. Client view of an entity

Overview

Entity beans allow their clients to access and manipulate data from a database in anobject-oriented manner. Multiple clients may access an entity object concurrently. Itis the responsibility of the container to synchronize the access by means oftransactions.

An entity bean may provide a remote client view, a local client view, or both. Whilethe remote client view is location dependent, the local client view is not. However, tobe the target of container-managed relationships (CMRs), entity beans need toprovide local interfaces.

While a crash of the JVM may result in a rollback of current transactions, it does notdestroy previously created entity objects nor does it invalidate the references to thehome and component interfaces held by clients.

Home interface

The home interface allows the client to create, find, and remove entity objects withinthe enterprise bean's home as well as to execute home business methods, whichare not specific to a particular entity bean. For each entity bean deployed in acontainer, the container provides a class that implements a home interface for theentity bean.

The following code illustrates the definition of the remote home interface of an entitybean.

public interface EmployeeHome extends EJBHome {public Employee create () throws RemoteException,

CreateException;public Employee findByPrimaryKey(String name) throws

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 107

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()

• void remove(Handle handle)

• void remove(java.lang.Object primaryKey)

The local home interface of an entity bean extends thejavax.ejb.EJBLocalHome interface. The local home methods must not throwRemoteException.

The method provided by EJBLocalHome is void remove(java.lang.ObjectprimaryKey).

Creating entity objectsThe create methods are used for creating new entities, which results in insertion ofnew rows in the database. For entity beans, create methods are optional in thehome interface. Typically, they take arguments, though it's not mandatory. Inaddition:

• There can be zero or more create methods.

• They must start with the prefix create.

• They have to match the ejbCreate() and ejbPostCreate() methodson the bean class.

• Their return type is the component interface of the bean.

• The throws clause must include javax.ejb.CreateException. Inaddition, java.rmi.RemoteException must be included if the homeinterface is remote.

• The throws clause may include additional application-level exceptions.

The following code illustrates a client looking up a home object reference andinvoking one of the create methods:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 34 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 objectsAn entity bean client needs to work with existing data more frequently than creatingnew entities. Multiple finder methods can be defined in the home interface for thepurpose of obtaining references to existing entities. In addition:

• There can be one or more finder methods.

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

• The return type must be the bean's component interface or a typerepresenting a collection of objects that implement the bean's componentinterface.

• The findByPrimaryKey() method must always be present and musthave a single argument that is of the same type as the entity bean'sprimary key type. This method cannot be overloaded.

• Every finder method in the home must have a matching method in thebean class that starts with the prefix ejbFind.

The following code illustrates multiple finder methods defined in the remote homeinterface 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) throwsRemoteException, FinderException;}

After looking up the home object of the entity using JNDI, a client can invoke a findermethod as shown by the code fragment below:

Account account = accountHome.findByPrimaryKey("100");

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 107

Removing entity objectsThe home interface provides two methods to remove entity objects.

The remove() method, which takes the javax.ejb.Handle as an argument, canbe called only by remote clients. The other version of the remove() method takesthe primary key of the entity bean as an argument. If the method is successful, thecontainer invokes the ejbRemove() method of the bean, removes thecorresponding data from the database, and invalidates the reference to the EJBObject of the entity. For example:

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 methodsHome business methods contain business logic that is not specific to an entity beaninstance. 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 thejava.rmi.RemoteException. Also, the arguments and return typesmust 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 remotecomponent interface must extend the javax.ejb.EJBObject interface, and thelocal component interface must extend the javax.ejb.EJBLocalObject

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 36 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

interface. These interfaces define the methods that allow the client to perform someuseful operations on an entity object's reference. The implementation for thesemethods is provided by the container.

Getting the home object referenceThe EJBObject interface defines getEJBHome() and the EJBLocalObjectinterface defines getEJBLocalHome(), which return the remote home and thelocal home object reference, respectively.

Getting the entity bean handleAn entity object's handle is a serializable object that identifies the entity object on anetwork. A remote client can obtain the entity object's handle by invoking thegetHandle() method on the remote component interface. The getHandle()method is only available on the remote component interface and not on the localone.

Getting the primary key of the entityEvery entity object has a unique identity within its home, which is denoted by itsprimary key. A client can determine the entity object's identity within its home byinvoking the getPrimaryKey() method on the component interface. If an entityobject has both a remote home interface and a local home interface, the result ofinvoking the getPrimaryKey() method on a reference to the entity object's remoteinterface and on a reference to the entity object's local interface is the same.

Comparing entity objectsA client can test whether two entity object references refer to the same entity objectby using the isIdentical() method. Alternatively, if a client obtains two entityobject references from the same home, it can determine if they refer to the sameentity by comparing their primary keys using the equals() method:

• boolean isIdentical(EJBObject obj): To be called by remoteclients

• boolean isIdentical(EJBLocalObject obj): To be called bylocal clients

Removing entity objectsThe remove() method provided by the EJBObject and EJBLocalObjectinterfaces can be used to remove entity objects.

Sample questions

Question 1:

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 107

Which of the following statements about the EJBLocalObject interface of an entitybean are true?

Choices:

• A. It does not define a getHandle() method.

• 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 andlocal home interface. The EJBLocalObject interface does not define agetHandle() method because the client and the enterprise bean are located in thesame EJB container. The Handle is a serializable reference, which allows a remoteclient 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 tocompare two local EJB Objects. So choices B and C are incorrect.

The EJBLocalObject() methods do not throw a RemoteException because thisinterface is used for co-located beans in the same JVM. However, they throwEJBException 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 (seeResources).

Question 2:

Read the following code (assume that MakeException is a valid applicationexception type):

public interface CarHome extends javax.ejb.EJBHome

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 38 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

{

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;

...

}

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 thetype of the local component interface.

• C. The return type of each create() method (that is, Car) must be thetype of the remote component interface.

• D. The create() methods are not allowed to declare applicationexceptions (MakeException) in their throws clause.

• E. The CarHome interface is allowed to declare overloaded createmethods.

• F. This home interface could also be used as the home interface of astateless session bean.

Correct choice:

C and E

Explanation:

Choice A is incorrect because the CarHome interface extends thejavax.ejb.EJBHome interface, which denotes a remote home interface. In orderfor CarHome to be a local home interface, it would need to extend thejavax.ejb.EJBLocalHome interface.

Choice B is incorrect because CarHome is a remote home interface. Eachcreate() 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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 107

application exceptions in their throws clause. Such exceptions are thrown if someproblem occurs during the bean creation process.

It is perfectly admissible for home interfaces of entity beans to declare overloadedcreate methods. This would also be allowed for stateful session beans, but not forstateless session beans, which must declare only one create() method that isnamed "create" and that takes no arguments. Therefore, choice E is correct whilechoice F is incorrect.

Please refer to sections 9.5 and 9.6 of the EJB 2.0 specification for further details(see Resources).

Summary

In this section, you learned the various ways in which clients interact with entitybeans. We saw the method types exposed by the home and component interfacesand the rules for defining them.

Note the significance of home business methods and how they differ from thebusiness methods defined in the component interface. Handles are only for remoteclients while primary keys can be retrieved by both remote and local clients.

Section 7. Component contract for CMP

Container-managed persistence entity beans

In a container-managed persistence (CMP) entity bean, the container generatesdatabase access code and manages synchronization of the bean state with theunderlying data. This provides a separation between the entity bean class and itspersistent representation, leading to data independence and bean portability. CMPalso allows multiple entity beans to have CMRs among themselves.

The Bean Provider uses the deployment descriptor to specify the CMP fields andCMR fields. The set of XML elements in the deployment descriptor describing theCMP and CMR fields is known as the abstract persistence schema of the entitybean. The Deployer maps the abstract persistence schema of a set of interrelatedentity bean classes into the physical schema used by the underlying data store by

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 40 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 descriptorusing the <cmp-field> and <cmr-field> elements respectively.

• Accessor methods must be defined in the bean class for the CMP andCMR fields.

• Accessor methods must be public and abstract, named with the first letterof the name of the CMP or CMR fields in uppercase, and prefixed by getor set.

• The accessor methods for a CMR field must be defined in terms of thelocal interface of the related entity bean.

• The Java types assigned to the CMP field are restricted to primitive typesand serializable types.

• The accessor methods for one-to-many or many-to-many relationshipsmust utilize the java.util.Collection or java.util.Setinterfaces.

• There must be no set accessor methods defined for the primary key CMPfields in the component interface of the entity bean.

• Accessor methods and collection classes for CMR fields must not beexposed 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();

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 107

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 havedefined abstract accessor methods for the container-managed fields, which map toactual database columns. The fields need to be specified in the deploymentdescriptor 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>

<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, andmay be either bi-directional or unidirectional. An entity bean that does not have alocal interface can have only unidirectional relationships from itself to the other entitybeans.

The relationships are defined in the <relationships> section of the deploymentdescriptor.

Within the <relationships> element, each entity-to-entity relationship is definedin a separate <ejb-relation> element, as illustrated below. Here EmployeeEJBand AddressEJB share a one-to-one unidirectional relationship:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 42 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

<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 bymeans of an <ejb-name> element contained in the<relationship-role-source> element. The <multiplicity> elementdescribes 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 usinga <cmr-field> element. A CMR field can use only the local interface of thereferenced bean. For every <cmr-field> element, there must be a pair of abstractaccessor methods in the bean class, as shown below. The name of the accessormethod is determined by the name of the relationship field in the deploymentdescriptor.

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 ismaintained by using the multiplicity defined for both beans. Consider the followingrelationships between instances of Employee and Address entity beans.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 43 of 107

It is not possible to share a single Address bean between two Employee beansbecause they share a one-to-one relationship.

Now suppose we make the assignmentemployeeB.setAddress(employeeA.getAddress());, as shown below:

Here the "Address 1" object reference was moved from "Employee A" to "EmployeeB."

Now consider the relationships between different instances of the Department beanand the Employee bean. The multiplicity for Employee is "Many" and for Departmentis "One."

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 44 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Now let us make the assignmentemployeeC.setDepartment(employeeA.getDepartment()); , as shownbelow:

Note that in this case, the "Department 1" object reference is shared betweenEmployee 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, ifthe <cascade-delete> element is specified for the target bean. The entity thatuses the <cascade-delete> element must have a multiplicity of "One" in therelationship. The container calls the ejbRemove() method on the target beaninstance due to the cascade delete operation and then removes its data from thedatabase.

Consider the relationship between an employee and his profile. Because<cascade-delete> has been specified for the ProfileEJB bean, removal of theEmployeeEJB bean instance will cause the container to automatically delete theassociated 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>

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 45 of 107

<cmr-field><cmr-field-name>profile</cmr-field-name>

</cmr-field></ejb-relationship-role><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 thelocal interface of the entity bean or a collection (either java.util.Collection orjava.util.Set) of the same, so these are the valid types of CMR fields of anentity bean. The set() method for the relationship must take as an argument theentity bean's local interface or a collection of the same.

Also note that the <cmr-field-type> element must be specified in thedeployment descriptor if the type of the <cmr-field> is java.util.Collection

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 46 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

or java.util.Set.

For more information, refer to section 10.3.2 of the EJB 2.0 specification (seeResources).

Question 2:

There are two entity beans, BeanA and BeanB, in a one-to-one unidirectionalrelationship. In addition, there are two references, ba1 and ba2, to instances ofBeanA and two references, bb1 and bb2, to instances of BeanB. Moreover, ba1 islinked to bb1 and ba2 is linked to bb2. If the statementba1.setBean2(ba2.getBean2()) is executed, which of the followingexpressions 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 oneinstance of Bean1 has a reference to one instance of Bean2, but the instance ofBean2 has no reference to the instance of Bean1. As the question states, ba1 islinked to bb1 and ba2 is linked to bb2.

The statement ba1.setBean2(ba2.getBean2()) retrieves the Bean2 object thatba2 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 theexecution of the above statement ba2 is not referencing anything. Thus,ba2.getBean2() returns null. Therefore, choice A is incorrect.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 47 of 107

Choices B and E are incorrect because the relationship is unidirectional andinstances 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 doesnot refer to any instance of Bean2. Thus, ba2.getBean2() returns null.

Choice D is correct because after the execution of the above statement the instanceof Bean2 (bb2) that was previously referenced by ba2 is now referenced by ba1.Thus, this expression returns true.

Choice F is incorrect because an instance of Bean1 does not have a reference toanother instance of Bean1.

Please refer to section 10.3.7.2 of the EJB 2.0 specification for further details (seeResources).

Summary

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

Section 8. CMP entity bean lifecycle

Overview

CMP entity beans support instance pooling, just like stateless session beans. Theyare also passivated and activated, but unlike the stateful session beans, the beanstate is not serialized.

The container interacts with the database when a new entity is to be created ordeleted. Similarly, it manages the transactions and the synchronization of the beanstate with the database. Let's examine the important events in the life of an entitybean instance and how the container interacts with the bean during these events.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 48 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

State diagram

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

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 beeninstantiated. The container instantiates the bean by calling theClass.newInstance() method on the bean class. Then an EntityContextobject is passed by invoking the setEntityContext() method. Now the beaninstance is in the Pooled state. In this state, the bean instance can service finder

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 49 of 107

methods, select methods, and home business methods, because they do not requirethe bean to have an identity. The bean instance can service entity-specific clientcalls when it is in the Ready state.

Two possible transitions from the Pooled to the ready state exist: through theejbCreate<METHOD>(...) and ejbPostCreate <METHOD>(...) methods, orthrough the ejbActivate() method. The container might decide to remove a beanfrom the pool and allow it to be garbage collected. At this point, theunsetEntityContext() 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 correspondingejbCreate<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 isinvoked.

• 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 correspondingejbFind() 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 beanhome.

• The container makes an EJB Object and returns its reference to theclient.

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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 50 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• 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 theEntityBean interface and the responsibilities of the bean provider and container indefining them.

setEntityContext()The entity object identity is not available in the setEntityContext() method. Theprogrammer can use this method to allocate any resources that are to be held by theinstance for its lifetime.

The container passes a reference to the EntityContext interface to the entitybean instance as an argument to this method. The container invokes this methodafter it creates an instance and before it puts the instance into the pool of availableinstances. This method is executed within an unspecified transaction context.

unsetEntityContext()

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 51 of 107

The container invokes this method when the container wants to reduce the numberof instances in the pool. After this method completes, the container must not reusethis instance. The programmer can use this method to free any resources that areheld 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 invokesa matching create<METHOD>() method on the entity bean's home interface. TheBean Provider can use this method to initialize the instance in this method from theinput arguments. He must not attempt to modify the values of CMR fields in thismethod because the primary key is not yet available. This method should return null.The ejbCreate<METHOD>>() methods and the subsequent database insertionoperations 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 thecorresponding 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 correspondingejbCreate<METHOD>() method. The container creates the primary key of theentity 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 duringthis method. The bean can use this method to acquire additional resources that itneeds while it is in the Ready state. The container invokes this method within anunspecified transaction context.

ejbPassivate()The ejbPassivate() method is invoked when the container decides todisassociate the instance from an entity object identity. The primary key of theassociated entity object is available to the instance during this method. The beancan use this method to release the resources that it acquired during theejbActivate() method. The container invokes this method within an unspecifiedtransaction context.

ejbRemove()The ejbRemove() method is invoked in response to a client-invoked remove

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 52 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

operation on the entity bean's home or component interface or as the result of acascade-delete operation.

The container synchronizes the state of the instance before it invokes theejbRemove() 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 itparticipates and then removes its persistent data. The ejbRemove() method andthe database delete operations are performed in the transaction context of theinvoked remove() method. The bean instance is in the Ready state whenejbRemove() is invoked and it will be entered into the pool when the methodcompletes.

ejbLoad()The ejbLoad() method is called when the container needs to synchronize the stateof an enterprise bean instance with the entity object's persistent state. This methodcan be used to recompute or initialize the values of any instance variables thatdepend on the entity bean's persistent state.

This method executes in the transaction context determined by the transactionattribute of the business method that triggered it.

ejbStore()The ejbStore() method is called when the container needs to synchronize thestate of the entity object in the database with the state of the enterprise beaninstance. This method is invoked in the same transaction context as the previousejbLoad() or ejbCreate() method invoked on the instance.

The Bean Provider can use the ejbStore() method to update the instance usingthe accessor methods before its persistent state is synchronized.

ejbFind<METHOD>()The ejbFind<METHOD>() methods are generated at the entity bean deploymenttime using the container provider's tools. The container invokes theejbFind<METHOD>() method on an instance when a client invokes a matchingfind<METHOD>() method on the bean home. The method is invoked on a pooledentity instance, which remains pooled even after the method call. This method isinvoked in the transaction context of the matching find<METHOD>() method.

ejbSelect<METHOD>()The ejbSelect<METHOD>() methods are not directly exposed to the client in thehome 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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 53 of 107

generated at deployment time using the container provider's tools. These methodsare typically called within a home or business method. They execute in thetransaction context determined by the transaction attribute of the invoking method.

ejbHome<METHOD>()The ejbHome<METHOD>() methods are invoked when the container selects theinstance to execute a matching client-invoked home business method. The pooledinstance, which is chosen for the method execution, remains in the pooled state afterthe execution of the home method. It is invoked in the same transaction context asthe triggering home method. The entity Bean Provider provides the implementationof the ejbHome<METHOD>(...) method. as an EJB-QL expression in thedeployment descriptor. Because the bean identity is not available within this method,the bean must not attempt to access its persistent state or relationships using theaccessor methods.

Sample questions

Question 1:

Select all the methods of an entity bean class that have a matching method in theirhome interface.

Choices:

• A. ejbCreate<METHOD>()

• B. ejbSelect<METHOD>()

• C. ejbLoad<METHOD>()

• D. ejbRemove<METHOD>()

• E. ejbFind<METHOD>()

Correct choice:

A and E

Explanation:

Choices A and E are correct because ejbCreate<METHOD>() must have amatching create<METHOD>() method in the home interface. Similarly,ejbFind<METHOD>() must have a matching find<METHOD>() method in thehome interface.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 54 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Choice B is incorrect because the ejbSelect<METHOD>() methods are internal tothe bean class and have no matching method in the home interface. They areusually invoked by an ejbHome<METHOD>() method or another method internal tothe bean class and not by the client.

Choices C and D are incorrect, as the ejbLoad() and ejbRemove() methodsmust not have any <METHOD> suffix. These methods are inherited from thejavax.ejb.EntityBean interface and must be implemented by the entity beanclass.

Please refer to sections 10.5.2 and 10.5.3 of the EJB 2.0 specification for furtherdetails (see Resources).

Question 2:

It is mandatory that certain resources held by an entity bean be released when thebean leaves the instance pool to be garbage collected. Which of the followingmethods 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 theremove() method on the bean's EJBObject or EJBHome. It notifies the entity beaninstance that its data is about to be removed from the database. The bean thentransitions into the Pooled state. So choice A is incorrect.

The ejbPassivate() method is invoked when a bean instance is disassociatedfrom its EJBObject and is moved to the Pooled state. The method that is calledwhen the bean instance moves from the instance pool to be garbage collected isunsetEntityContext(). After this method is called, the bean instance is eligiblefor garbage collection. Therefore, choice C is correct.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 55 of 107

The finalize() method should not be used to release the resources because itmight not be called at all. Hence, choice D is incorrect.

For more information, refer to section 10.5 of the EJB 2.0 specification (seeResources).

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 fromthat of session beans. You should be aware of the exact sequence of events foreach state transition of the bean instance.

We also discussed the methods defined in the bean class and the responsibilities ofthe Bean Provider and container in each case.

Section 9. Entity beans

EntityContext interface

The EntityContext interface allows an entity bean instance to access itscontainer-provided runtime context. After a bean instance is created, the containerinvokes the setEntityContext() method on the instance, passing a reference toits EntityContext. As the bean instance is switched between EJB Objects by thecontainer, the information obtained from EntityContext (such as the primary key)is subject to change.

The EntityContext interface extends javax.ejb.EJBContext, which is alsoextended by the SessionContext, used by session beans.

EntityContext methods

Let us examine the methods that can be invoked by the entity bean on itsEntityContext reference.

Methods defined in EntityContext are as follows:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 56 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• EJBLocalObject getEJBLocalObject(), which returns a referenceto the local component interface of the bean instance.

• EJBObject getEJBObject(), which returns a reference to the remotecomponent interface of the bean instance.

• Object getPrimaryKey(), which returns the primary key of the EJBObject that is currently associated with this bean instance. It is the onlymethod in the EntityContext interface that is not declared in theSessionContext interface because session beans cannot have primarykeys.

Methods inherited by EntityContext from EJBContext are as follows:

• EJBHome getEJBHome(), which returns a reference to the entity bean'sremote home interface.

• EJBLocalHome getEJBLocalHome(), which returns a reference to theentity bean's local home interface.

• javax.security.Principal getCallerPrincipal(), whichreturns an instance of a java.security.Principal that identifies theinvoker of the method.

• boolean isCallerInRole(String rolename), which returns true ifthe caller of the entity bean instance has a particular role.

• void setRollbackOnly(), which marks the current transaction forrollback.

• boolean getRollbackOnly(), which allows the bean instance to testif the current transaction has been marked for rollback.

• javax.transaction.UserTransaction getUserTransaction(),which returns an instance of ajavax.transaction.UserTransaction interface. Entity beaninstances must not call this method because they do not support BMTdemarcation.

Operations allowed in EntityBean methods

Let's look at which operations are allowed to be performed in the methods defined inan entity bean. If an entity bean instance attempts to invoke a method of theEntityContext interface, and access is not allowed, the container throws ajava.lang.IllegalStateException exception.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 57 of 107

You are not allowed to invoke the getEJBObject(), getEJBLocalObject(),and getPrimaryKey() methods in the methods in which there is no entity objectidentity 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 availableuntil the ejbPostCreate<METHOD>() method is invoked.

The getCallerPrincipal() and isCallerInRole() methods ofEntityContext are not allowed to be invoked in methods in which the containerdoes not have a client security context, which include the setEntityContext(),unsetEntityContext(), ejbPassivate(), and ejbActivate() methods.

The getRollbackOnly() and setRollbackOnly() methods, which allowgetting and setting of the transaction status, are not allowed in methods for whichthe container does not have a meaningful transaction context, which include thesetEntityContext(), unsetEntityContext(), ejbPassivate(), andejbActivate() methods.

Accessing resource managers and enterprise beans is not allowed in theejbPassivate() and ejbActivate() methods because there is no meaningfultransaction context or client security context.

The getEJBHome() and getEJBLocalHome() methods can be invoked in all thebean 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 areconsidered identical.

A primary key can be of two types: Single field keys or composite keys. A single fieldprimary key maps to a single persistence field in the entity bean. A compositeprimary 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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 58 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Single field primary keysWe can use a single CMP field of the primary key by declaring the field name andthe class name in the deployment descriptor. Typically, String and wrapper classesare used as single field primary keys because they are atomic. The<primkey-field> element of the deployment descriptor specifies thecontainer-managed field of the entity bean. The field type must be the same as theprimary key type. The <prim-key-class> element contains the fully qualifiedname of an entity bean's primary key class.

For example, we have the "custId" CMP field as the primary key for theCustomerBean entity bean shown below:

public abstract class CustomerBean implements EntityBean{

// Accessor methods in the bean class for the primary keypublic abstract Integer getCustId();public abstract void setCustId(Integer id);...

}

// Specifying the primary key details in the deploymentdescriptor

<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 keysA composite primary key is made up of the CMP fields of the bean. The class mustbe public and must have a public constructor with no parameters. All fields in theprimary key class must be declared as public, and their names must correspond tothe entity bean field names that comprise the key. The <primkey-field> elementis not used for composite keys.

The <prim-key-class> element contains the fully qualified name of an entitybean'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;

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 59 of 107

}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 keysThe bean developer can defer declaring the primary key to the deployer, whichallows the deployer to choose a database-specific key at deployment time. TheBean Provider must specify the primary key class in the deployment descriptor astype java.lang.Object. The container generates the primary key value when theentity bean instance is created.

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 thegetEJBObject(), getEJBLocalObject(), and getPrimaryKey() methodscan be successfully invoked (that is, without throwing an exception) on the entitycontext object.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 60 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The methods from which these methods can be invoked areejbPostCreate<METHOD>(), ejbRemove(), ejbActivate(),ejbPassivate(), ejbLoad(), ejbStore(), and business methods. Thequestion 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 (seeResources).

Question 2:

What are the requirements for a primary key class that maps to multiple fields of anentity bean class?

Choices:

• A. The primary key class must be private and be an inner class of theentity bean class.

• B. The primary key class must be public and abstract because thecontainer will be responsible for providing an implementation of theprimary key classes.

• C. All fields of the primary key class must follow the JavaBeansconventions -- that is, the fields must be private, and public accessor ormutator methods must be provided.

• D. All fields of the primary key class must be declared public (and thusbreak the encapsulation of the primary key class).

• E. The container-managed field names of the entity bean declared in thedeployment descriptor can be used as field names in the primary keyclass.

• F. ba1.getBean1() == null

Correct choice:

D and E

Explanation:

Choice A is incorrect because the primary key class must be declared public andnot private.

Choice B is incorrect because the primary key class does not need to be declared

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 61 of 107

abstract. The container should be allowed to use the primary class without havingto extend it.

Choice C is incorrect because there is no such requirement. All fields of the primarykey class must be declared public, even if this means that the encapsulation of theclass is broken. Hence, choice D is correct.

Choice E is also correct because the primary key class is not allowed to declarefields having names that are different from the names of the container-managedfields 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 (seeResources).

Summary

This section covered the methods defined in the EntityContext interface, whichis the interface the entity bean instance uses to interact with the container. Someoperations may require a valid transaction context or security context to be availablewhen they are invoked, while some others might work only for CMTs. Hence, it isimportant to understand which operations are allowed to be performed within eachcallback method of the bean and why.

We also discussed the rules regarding the primary keys of entity beans and how todefine the single field and composite keys.

Section 10. EJB-QL

Purpose of EJB-QL

EJB-QL is a query specification language for the finder and select methods of CMPentity beans. This language is portable across databases and data schemas. It ispossible to parse and validate EJB-QL queries before entity beans are deployedbecause the language is defined in terms of the abstract persistent schema of theentity beans. These queries are written by the entity Bean Provider in thedeployment descriptor. Container tools then translate these queries into the targetlanguage of the underlying data store.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 62 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

EJB-QL queries can be used in two different ways:

• As queries for selecting entity objects through finder methods defined inthe home interface

• As queries for selecting entity objects or other values derived from anentity bean's abstract schema type through select methods defined on theentity 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 tobe selected

• A FROM clause, which provides declarations that designate the querydomain

• An optional WHERE clause, which may be used to restrict the resultsreturned by the query

All standalone identification variables in the SELECT clause must be qualified by theOBJECT operator. For example, the following query statement returns all thecustomers:

SELECT OBJECT(c) FROM Customer c

EJB-QL also allows SELECT clauses to return CMP or CMR fields. Paths cannavigate over one or more CMR fields to end at either a CMR or CMP single-valuedfield. In the example below, name is a CMP field, and address is a CMR field thatcontains the city CMP field:

SELECT c.name FROM Customer cSELECT c.address.city FROM Customer c

The IN operator allows the representation of individual elements in acollection-valued CMR field. The following query returns the phone numbers of allthe customers:

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 63 of 107

SELECT OBJECT (p) FROM Customer c, IN (c.phones) p

Note that path expressions cannot navigate beyond CMP fields. The following queryis invalid because city is a CMP field of the Address bean:

SELECT c.address.city.name FROM Customer cThe SELECT clause cannot return multi-valued expressions, so the following query isinvalid:

SELECT o.lineItems FROM Order o

The following query is invalid because navigating across a collection-basedrelationship field is not allowed:

SELECT c.phones.no FROM Customer c

Conditional expressionsWe can use conditional expressions in the WHERE clause to restrict the results of thequery.

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 thefinder or select method for which it is defined, as shown in the following example:

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. TheDISTINCT keyword is used to specify that duplicate values must be eliminated fromthe query results.

BETWEEN expressions

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 64 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The BETWEEN clause is used to specify a range of values. It may be used only onnumeric 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 expressionsThe IN operator in the WHERE clause tests for membership in a list of literal stringvalues:

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 secondreturns those who are not from these states.

LIKE expressionsThe 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 standsfor 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"

Using EJB-QL with finder methods

Finder methods are defined in the home interface of an entity bean and return asingle entity object or a collection of entity objects. Every finder method must bemapped 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> elementdeclares the EJB-QL statement.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 65 of 107

Every entity bean referenced in an EJB-QL statement must have an identifier knownas "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 asshown 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>

Using EJB-QL with select methods

A select method is a special type of query method, not directly exposed through theclient view.

It is declared as abstract in the entity bean class and can return values thatcorrespond to any CMP or CMR field type. Like find methods, select methods candeclare zero or more arguments. An ejbSelect() method definition is shown inthe following example:

public abstract class AddressBean implements EntityBean{public abstract Collection ejbSelectAll() throws FinderException;

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 66 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

}

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 returnEJBLocalObject or a collection of EJBLocalObjects. If theejbSelect<METHOD>() method returns an EJBObject or collection ofEJBObjects, 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 beaninstance on which it is invoked, so it can be used to query across all the entity beansdeclared in the same deployment descriptor.

Sample questions

Question 1:

Select all the expressions that are semantically equivalent to the BETWEENexpression given below:

person.age BETWEEN 20 and 25

(Assume that person is an identification variable identifying a bean that has a CMPfield called age.)

Choices:

• A. person.age > 20 AND person.age < 25

• B. person.age >= 20 AND person.age < 25()

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 67 of 107

• C. person.age > 20 AND person.age <= 25

• D. person.age >= 20 AND person.age <= 25

Correct choice:

D

Explanation:

In EJB-QL, BETWEEN expressions always include the values at the limits. In thiscase, BETWEEN 20 and 25 really means any values between 20 and 25, bothinclusive. Therefore, the only correct choice is D.

Please refer to section 11.2.7.7 of the EJB 2.0 specification for further details (seeResources).

Question 2:

Which of the following statements about EJB-QL are correct?

Choices:

• A. EJB-QL queries are portable across databases, data schemas, andEJB 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 pathexpressions.

• D. SELECT clauses may return a single or collection-based CMR field.

Correct choice:

A and C

Explanation:

EJB-QL uses the abstract persistence schema of entity beans, including theirrelationships, for its data model. This makes the queries portable across EJBcontainers.

At deployment time, the EJB-QL statements are translated into native data accesscode, so they are independent of the underlying data store structure and schema.Thus, choice A is correct.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 68 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

EJB-QL queries can only fetch data from the database; they cannot be used forupdates and insertions. So choice B is incorrect.

All standalone identification variables in the SELECT clause must be qualified by theOBJECT operator. However, the SELECT clause must not use the OBJECT operatorto 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-basedrelationship field. So choice D is incorrect.

For more information, refer to section 11 of the EJB 2.0 specification (seeResources).

Summary

This section demonstrated how to use EJB-QL queries to access the data requiredby the finder and select methods of an entity bean. We discussed the correct andincorrect syntaxes for an EJB-QL query and how to define such queries in thedeployment descriptor. We reviewed how the results of the query can be restrictedusing conditional expressions, BETWEEN expressions, LIKE expressions, andcomparison expressions.

Section 11. MDB component contract

Message-driven beans

Message-driven beans (MDBs) are asynchronous JMS message consumers. Theydo 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 toreceive the message or process it. After sending the message, the client cancontinue doing its job. However, there is no guarantee that the bean will receive themessages in the same order in which they have been sent.

MDB lifecycle

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 69 of 107

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() onthe MDB class to create a new instance. Next, the container callssetMessageDrivenContext() followed by ejbCreate() on the instance. Thebean 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 multipleinstances of the same type.

The container invokes ejbRemove() on the bean instance when it no longer needsthe instance. The bean instance can perform clean up operations here.

Interfaces and methods

The MDB must implement the javax.ejb.MessageDrivenBean andjavax.jms.MessageListener interfaces.

MessageDrivenBeanThe MessageDrivenBean interface defines lifecycle event notification methodsinvoked by the container on the bean instance.

The methods defined by this interface are as follows:

• void setMessageDrivenContext(MessageDrivenContext ctx)

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 70 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• void ejbRemove()

The setMessageDrivenContext() method, which is invoked at the beginning ofthe bean lifecycle, provides the MDB instance with a reference to itsMessageDrivenContext.

The ejbRemove() method is called at the end of the bean lifecycle, before it isgarbage collected.

MessageListenerA MessageListener object is used to receive asynchronously deliveredmessages.

The only method defined by this interface is void onMessage(Messagemessage). It is called by the bean's container when a message has arrived for thebean to service. It contains the business logic that handles the processing of themessage.

MessageDrivenContextThe MessageDrivenContext interface gives the MDB instance access to theinstance's runtime context maintained by the container. The context object remainsassociated with the instance for the lifetime of the instance. This interface containsonly methods inherited from EJBContext.

The methods of MessageDrivenContext that are allowed to be called by MDBsare as follows:

• public boolean getRollbackOnly(), which tests whether thetransaction has been marked for rollback

• public void setRollbackOnly(), which marks the currenttransaction for rollback

• public UserTransaction getUserTransaction(), which returnsthe UserTransaction reference

The getRollbackOnly() and setRollbackOnly() methods must be invokedonly 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.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 71 of 107

Configuring the MDB

We need to configure some elements in the deployment descriptor to enable theMDB to listen to JMS messages.

JMS destinations can be Queues or Topics. The<message-driven-destination> element indicates whether an MDB isintended for a Queue or a Topic. The Bean Provider specifies the<message-driven-destination> element to advise the Deployer whether toassociate the MDB with a Queue or a Topic.

Durable topic subscriptions, as well as queues, ensure that messages are notmissed even if the EJB server is not running. The <subscription-durability>element specifies whether a JMS topic subscription is intended to be durable ornon-durable.

The following example illustrates the deployment descriptor configuration for anMDB:

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

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

The JMS message service expects the container to acknowledge if a message hasbeen successfully delivered to the MDB. If an acknowledgement is not received, theJMS service resends the same message. If the bean uses CMT transactiondemarcation, the message acknowledgment is handled automatically as a part of thetransaction commit. For beans using BMT transaction demarcation, the BeanProvider can indicate in the <acknowledge-mode> element whether JMSAUTO_ACKNOWLEDGE or DUPS_OK_ACKNOWLEDGE should be used. UsingAUTO_ACKNOWLEDGE automatically acknowledges the successful delivery of amessage. Using DUPS_OK_ACKNOWLEDGE instructs the container to lazilyacknowledge the delivery of messages, which makes the server more efficient at therisk of duplicate messages.

Responsibilities of the Bean Provider

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 72 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The Bean Provider needs to follow these guidelines to ensure that an MDB can bedeployed in any EJB container.

Requirements of the MDB class

• The class must implement MessageDrivenBean andMessageListener 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 typejavax.jms.Message.

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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 73 of 107

Responsibilities of the container provider

The container provider is responsible for providing the deployment tools and formanaging the MDB instances at runtime. The container must ensure that the beaninstances 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 adurable subscription. The container must also follow the rules with respect totransaction scoping, security checking, and exception handling.

Sample questions

Question 1:

Which of the following methods of the MessageDrivenContext interface areavailable for use by the MDBs?

Choices:

• A. getCallerPrincipal()

• B. getEJBHome()

• C. getRollbackOnly()

• D. isCallerInRole()

Correct choice:

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 homeinterface. MDBs are anonymous, that is they don't have a visible client identity. Sothe getCallerPrincipal() and isCallerInRole() methods, which need thesecurity 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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 74 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Resources).

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 beimplemented by any MDB class. The onMessage() method is defined in theMessageListener interface. This method passes the messages to the MDB by thecontainer. The MessageDrivenBean interface defines two callback methods --setMessageDrivenContext() and ejbRemove(). ThesetMessageDrivenContext() method is called at the beginning of the MDB'slifecycle and provides the bean with a reference to its MessageDrivenContextinterface.

The MessageDrivenContext interface extends the EJBContext interface. Oneof these methods is setRollbackOnly().

Only Mandatory and Never may cause the EJB container to throw an exception,so the remaining options are incorrect.

For more information, refer to section 15.4 of the EJB 2.0 specification (seeResources).

Summary

This section covered message-driven beans. The main point to remember about

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 75 of 107

MDBs is that they do not expose a client view. Therefore, their lifecycle is entirelycontrolled by the container, they do not have component or home interfaces, and themethods that can be invoked on the MessageDrivenContext are limited. Alsonote that MDB methods must not throw application exceptions, because there aren'tany clients to handle them. For this objective, we do not need to know much aboutthe Java Messaging Service, but it is necessary to be aware of the MDBconfiguration elements in the deployment descriptor.

Section 12. Transactions

Overview

Transactional systems ensure that a unit of work either fully completes or is fullyrolled back. The EJB architecture supports distributed transactions, but not nestedones. In nested transactions, a new transaction can be started, while a transaction iscurrently active.

In EJB development, the Bean Provider can choose between using programmatictransaction demarcation in the enterprise bean code (BMT demarcation) ordeclarative 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. Anentity bean can use only CMT.

Container-managed transactions

The EJB container is responsible for managing transaction boundaries in the case ofa CMT bean. When a client calls a method on an enterprise bean, the new methodcan run in the caller's transaction, start a new transaction, or run without atransaction. The action taken by the EJB container in this case is decided by thetransaction attribute defined for the method.

Transaction attribute basicsTransaction attributes must be given for business methods in the case of both entityand session beans. They must not be specified for the methods of a session bean'shome interface because these methods are not considered as part of a client's

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 76 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

transaction. This rule, however, is not the case for entity beans, in which homeinterface methods like create() and remove() involve database operations andare hence transactional. For an MDB, the transaction attribute can only be specifiedfor 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 ofthese influences the transactional behavior of the method:

• Required: If the EJB client is not associated with a transaction, thecontainer will automatically begin a new transaction for the bean method.Otherwise, it uses the existing client transaction.

• RequiresNew: The container always creates a new transaction beforeinvoking a method on the bean.

• NotSupported: The transactional context of the calling client is notpropagated to the enterprise bean. Instead, the client transaction issuspended and the bean method runs within an unspecified transactioncontext.

• Supports: If the client is associated with a transaction context, the beanruns within the same transaction context. Otherwise, the bean methodruns within an unspecified transaction context.

• Mandatory: If a remote client invokes a bean method without ameaningful transaction context, the container throwsTransactionRequiredException. If a local client invokes a beanmethod without a meaningful transaction context, the container throwsTransactionRequiredLocalException. Otherwise, the beanmethod runs within the client's transaction context.

• Never: If a remote client invokes a bean method with a meaningfultransaction context, the container throws ajava.rmi.RemoteException. If a local client invokes a bean methodwith a meaningful transaction context, the container throws ajavax.ejb.EJBException. Otherwise, the bean method runs within anunspecified transaction context.

Restrictions on transaction attributesFor MDBs, only the Required and NotSupported transaction attributes may beused because they have no calling clients and hence the other attributes do notapply.

If an enterprise bean implements the SessionSynchronization interface, only

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 77 of 107

the transaction attributes Required, RequiresNew, or Mandatory are allowed, toensure that the method is participating in a transaction. For portable entity beansthat use EJB 2.0 CMP also, only the Required, RequiresNew, or Mandatorytransaction attributes must be used.

CMT beans may use the setRollbackOnly() method on its EJBContext tomark a transaction for rollback, and the getRollbackOnly() method to test if atransaction has been marked for rollback. For these operations to work, the methodin which they are invoked should be in a transaction, so its attribute must beRequired, RequiresNew, or Mandatory.

Roles and responsibilitiesThe Bean Provider must use the <transaction-type> element to declarewhether the bean uses CMT or BMT demarcation. The Application Assembler usesthe <container-transaction> element to define the transaction attributes. TheDeployer is responsible for ensuring that the methods of the enterprise beansdeployed with CMT demarcation have been assigned a transaction attribute.

In the following example, all the methods of CustomerEJB have been given thetransaction attribute Required, except the addBonus() method, which has beengiven 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 clientview and they run asynchronously.

If the methods are overloaded, the optional <method-params> and

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 78 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

<method-param> elements allow you to identify the appropriate method.

For example, if we want to specify a different transaction attribute for theaddBonus(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>

Bean-managed transactions

In the case of BMTs, the bean itself manages transactions programmatically in thebusiness methods. The Bean Provider uses thejavax.transaction.UserTransaction interface to explicitly demarcatetransactions. A bean instance that starts a transaction must complete the transactionbefore 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 thetransactional code, and finally we invoke the commit() method to end thetransaction. 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, asshown below:

UserTransaction t = (UserTransaction)jndiContext.lookup("java:comp/UserTransaction");

Restrictions on using BMT

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 79 of 107

A BMT bean can only run in the transactions that the bean has started itself. If atransactional client invokes the methods of a BMT bean, the incoming transaction issuspended.

A stateful session bean instance may, but is not required to, commit a startedtransaction before a business method returns. A stateless session bean instancemust commit a transaction before a business method returns, because the sameinstance is not dedicated for multiple method calls. An MDB instance must commit atransaction before the onMessage() method returns.

A BMT enterprise bean must not use the getRollbackOnly() andsetRollbackOnly() methods of the EJBContext interface. Instead, it must usethe getStatus() and setRollbackOnly() methods of the UserTransactioninterface.

Methods of UserTransactionThe UserTransaction interface defines the following methods that are invoked bythe bean to manage the transactions:

• void begin(): Creates a new transaction and associates it with thecurrent thread.

• void commit(): Completes the transaction associated with the currentthread.

• void rollback(): Rolls back the transaction associated with thecurrent thread.

• void setRollbackOnly(): Modifies the transaction associated withthe current thread such that the only possible outcome of the transactionis to roll back the transaction. Invoking this method is a signal to the othertransaction participants that the transaction will never commit.

• int getStatus(): Returns the status of the transaction associated withthe current thread. Using this method, the bean can find out if thesetRollbackOnly() method has been invoked on the transaction.

• void setTransactionTimeout(int seconds): Modifies thetimeout value that is associated with the transactions started by thecurrent thread with the begin method.

Sample questions

Question 1:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 80 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 havetransaction 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 theonMessage() method.

• E. If the transaction attribute of a bean method is Mandatory and aremote client invokes it without a transaction, aTransactionMandatoryException is thrown.

Correct choice:

A and D

Explanation:

The create() and remove() methods in session beans do not have transactionattributes, only the business methods have. So choice A is correct.

Nested transactions and isolation levels are not supported in EJB 2.0, so choices Band 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 clientinvokes it without a transaction, a TransactionRequiredException is thrown(there is no such exception as TransactionMandatoryException). So choice Eis incorrect.

Question 2:

Which of the following transaction attributes may cause the container to throw anexception whenever the transaction context does not satisfy their requirements?

Choices:

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 81 of 107

• A. Required

• B. RequiresNew

• C. Never

• D. Mandatory

• E. Supports

• f. NotSupported

Correct choice:

C and D

Explanation:

The transaction attribute Mandatory behaves the same way as the Requiredattribute when a client calls with a transaction context. However, if the client makes acall in an unspecified transaction context, the EJB container is required to throw thejavax.transaction.TransactionRequiredException exception if the clientis a remote client or the javax.ejb.TransactionRequiredLocalException ifthe client is a local client.

The transaction attribute Never behaves the same way as the NotSupportedattribute when a client calls without a transaction context. However, if the clientmakes a call within a transaction context, the EJB container is required to throw thejava.rmi.RemoteException if the client is a remote client or thejavax.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 (seeResources).

Summary

In this section, we discussed the effect of CMT demarcation as compared to that ofBMTs in enterprise beans. It is important to remember that entity beans must notuse BMT demarcation. Similarly, we saw which transaction attributes are applicablefor MDBs, beans implementing SessionSynchronization interfaces, and so on.For each bean type, we need to be aware of the methods for which transaction

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 82 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

attributes must be specified. Finally, we showed you the significance of theUserTransaction() methods, which enable BMT beans to programmaticallymanage transactions.

Section 13. Exceptions

Application exceptions

An application exception is an exception defined in the throws clause of a method inthe bean's home or component interface. An application exception class must be adirect or indirect subclass of java.lang.Exception, but neither ofjava.lang.RuntimeException nor java.rmi.RemoteException.

These exceptions typically indicate application-level problems such as illegal valuesof the input arguments to a business method. They should be reported to the clientwithout any modification. An application exception does not cause an automaticrollback of an ongoing transaction, and the client can continue to work with the beaninstance.

System exceptions

A system exception is an exception that the client does not expect or is not expectedto recover from. All unchecked exceptions as well asjava.rmi.RemoteException belong to this category. System-level errors may beencountered during the execution of a session or an entity bean business method,an MDB onMessage() method, or a container callback method. Some examplesinclude:

• Failure to obtain a database connection

• JNDI exceptions

• Unexpected RemoteException from invocation of other enterprisebeans

• Unexpected RuntimeException

• JVM errors

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 83 of 107

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

Responsibilities of the container provider

The Bean Provider expects the container to perform certain tasks when exceptionsare thrown. Let's examine these in detail for different situations.

Application exceptionsIf the bean method is running in the context of the caller's transaction, the containerre-throws the exception to the client. The client can continue working with thetransaction but cannot commit the transaction if the bean instance has invoked thesetRollbackOnly() method. This situation does not arise in the case of beansusing BMT demarcation because transactions cannot propagate into a BMT bean.

If the bean method runs in the context of a container-initiated transaction, thecontainer attempts to commit the transaction and then re-throws the exception.However, if the bean instance has called setRollbackOnly(), then the containerrolls back the transaction and re-throws the exception. For beans executing withinan unspecified transaction context, the exception is simply re-thrown.

MDBs must not throw application exceptions, because they don't have any clientview and they run asynchronously.

System exceptionsFor all bean types, system exceptions are logged, the existing transaction is markedfor rollback, and the bean instance is discarded.

If the bean was executing within a client-initiated transaction, the container throwsTransactionRolledbackException to remote clients andTransactionRolledbackLocalException to local clients. This situation doesnot arise in the case of beans using BMT demarcation, because transactions cannotpropagate into a BMT bean.

For beans running in container-initiated transactions or within an unspecifiedtransaction context, RemoteException is thrown to remote clients andEJBException to local clients.

The container does not throw any exception in the case of MDBs, because they donot have any client view.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 84 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Responsibilities of the Bean Provider

Let's analyze the responsibilities of the Bean Provider with respect to exceptionhandling.

Application exceptions

• The application exception class must directly or indirectly extendjava.lang.Exception, but not RuntimeException orRemoteException.

• If a business logic exception occurs in the bean code, the Bean Providermust throw it to the container as the appropriate application exception.Accordingly, the application exception must be declared in the throwsclause of the business method in the component interface.

• If the Bean Provider catches an application exception and figures out thatthe transaction cannot be committed, he callsEJBContext.setRollbackOnly() for CMT beans orUserTransaction.setRollbackOnly() for BMT beans, beforere-throwing the exception further.

• The Bean Provider must ensure that the bean instance is in a state suchthat a client's attempt to continue and/or commit the transaction does notresult in the loss of data integrity.

System exceptions

• If the bean method encounters a RuntimeException or error, it shouldsimply propagate the error to the container.

• If the bean method performs an operation that results in a checkedexception that the client is not expecting, the bean method should wrapthe original exception within a javax.ejb.EJBException and throwthe latter to the container.

• javax.ejb.EJBException is a subclass of thejava.lang.RuntimeException, and therefore does not have to belisted 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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 85 of 107

programming.

Standard application exceptions are:

• CreateException

• DuplicateKeyException

• RemoveException

• FinderException

• ObjectNotFoundException

CreateExceptionThis exception can be thrown by the container to indicate a problem during the beancreation. This method must be declared in the throws clauses of all the createmethods declared in an enterprise bean's home interface and all theejbCreate<METHOD>() methods declared in the enterprise bean's class.

DuplicateKeyExceptionThe javax.ejb.DuplicateKeyException exception is thrown if an entity objectcannot be created because an entity with the same key already exists. Thisexception is thrown by the create methods defined in an entity bean's homeinterface. It is a subclass of javax.ejb.CreateException.

RemoveExceptionThe javax.ejb.RemoveException exception may be thrown when attempting toremove a bean when the enterprise bean or the container does not allow it to beremoved.

FinderExceptionThe finder methods of an entity bean throw this exception to report a failure whenfinding the requested entity (or entities). It must be included in the throws clause ofevery finder method of the entity bean's home interface.

ObjectNotFoundExceptionThe javax.ejb.ObjectNotFoundException exception is thrown by asingle-entity finder method to indicate that the specified entity does not exist. It is asubclass of javax.ejb.FinderException.

Some of the most common system exceptions are:

• EJBException

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 86 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• IllegalStateException

• NoSuchEntityException

• TransactionRequired(Local)Exception

• TransactionRolledback(Local)Exception

EJBExceptionThe javax.ejb.EJBException exception is thrown by the bean to the containerto report that the invoked business or callback method could not completesuccessfully because of some unexpected error. The container may throw it to localclients when it catches a system exception. It is a subclass ofjava.lang.RuntimeException.

IllegalStateExceptionThis exception is also a subclass of java.lang.RuntimeException. Thecontainer throws this exception to the enterprise bean to signal that a method hasbeen invoked at an illegal or inappropriate time, like calling setRollbackOnly()within a method executing in an unspecified transaction context.

NoSuchEntityExceptionThe javax.ejb.NoSuchEntityException exception is thrown by an entity beaninstance to report that the referenced entity was removed from the database. Thisexception may be thrown by ejbLoad(), ejbStore() and any business methods.It is a subclass of javax.ejb.EJBException.

TransactionRequiredException/TransactionRequiredLocalExceptionIf a bean method marked with the Mandatory transaction attribute is invoked by anon-transactional client method,javax.transaction.TransactionRequiredException is thrown if the clientis remote and javax.ejb.TransactionRequiredLocalException is thrown ifthe client is local. TransactionRolledbackException is a subclass ofjava.rmi.RemoteException andTransactionRolledbackLocalException is a subclass ofjavax.ejb.EJBException.

TransactionRolledbackException/TransactionRolledbackLocalExceptionIf a client receives javax.transaction.TransactionRolledbackExceptionor javax.ejb.TransactionRolledbackLocalException, the client knows forcertain that the transaction has been marked for rollback.TransactionRolledbackException is a subclass ofjava.rmi.RemoteException, whileTransactionRolledbackLocalException is a subclass ofjavax.ejb.EJBException.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 87 of 107

Sample questions

Question 1:

Which exception would a client receive if a javax.ejb.EJBException is thrownfrom 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 questionstatement. First, we know that the bean throws a javax.ejb.EJBException, sowe 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 wouldhave thrown javax.ejb.TransactionRequiredLocalException), so choiceF 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 transactionthrows a javax.ejb.EJBException, the EJB container is required to throwjavax.ejb.TransactionRolledbackLocalException, as mentioned in Table15 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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 88 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

further details (see Resources).

Question 2:

In which of the following cases will the EJB container discard a bean instance whenan application exception is thrown from one of the bean's method?

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 fromone of the bean's methods.

Please refer to section 18 of the EJB 2.0 specification for further details (seeResources).

Summary

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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 89 of 107

Section 14. Enterprise bean environment

Environment entries

The enterprise bean's environment allows the bean behavior to be customizedwithout the need to access or change the bean's source code. The containerprovides an implementation of the JNDI naming context that stores the enterprisebean environment.

Environment entries are variables whose values are specified in the deploymentdescriptor and looked up by the bean using JNDI interfaces. Each enterprise beandefines 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 Providerin the deployment descriptor.

For example, the following elements in the deployment descriptor declare anenvironment 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 containsthe <env-entry> element. The environment entry values may be any of thefollowing Java types:

• String

• Character

• Integer

• Boolean

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 90 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• Double

• Byte

• Short

• Long

• 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 bythe bean are set to meaningful values. The Deployer uses the tools provided by thecontainer to create the environment entries that are declared in the enterprise bean'sdeployment descriptor by the Bean Provider. He may set different values for theenterprise 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 andlooks up the home interface of the referenced enterprise bean in the enterprisebean's environment using JNDI. The Deployer binds the EJB references to the realJNDI names of the enterprise bean homes in the target operational environment.

Local EJB references are declared using the <ejb-local-ref> element andremote EJB references, using the <ejb-ref> element. The EJB specificationrecommends -- but does not require -- that all references to other enterprise beansbe 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 EJBreference Emp within the subcontext ejb:

<entity>...<ejb-ref>

<ejb-ref-name>ejb/Emp</ejb-ref-name>

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 91 of 107

<ejb-ref-type>Entity</ejb-ref-type><home<EmpHome</home><remote>EmpRemote</remote>

</ejb-ref>...</entity>

A client can look up the home interface of the referenced bean using the followingcode:

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 deploymentdescriptor 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 bedefined 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

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 92 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

of enterprise beans that exist in the operational environment

• Must ensure that the target enterprise bean is type-compatible with thetypes declared for the EJB reference

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

Resource manager connection factories

A resource manager connection factory is an object that is used to createconnections to a resource manager like a database. The enterprise bean code canrefer to resource factories using logical names called resource manager connectionfactory references.

The Bean Provider declares the resource manager connection factory references inthe deployment descriptor using the <resource-ref> element and looks up theresource manager connection factory object using JNDI. A resource managerconnection factory reference is scoped to the enterprise bean whose declarationcontains the <resource-ref> element, so there aren't any naming conflicts withother 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 thejavax.jms.TopicConnectionFactory: For obtaining JMSconnections

• javax.mail.Session resource manager connection factory type: Forobtaining JavaMail connections

• java.net.URL resource manager connection factory type: For obtainingURL connections

The following example shows how we define a DataSource reference in thedeployment descriptor:

<resource-ref><res-ref-name>jdbc/OrderAppDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth<Container</res-auth>

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 93 of 107

<res-sharing-scope>Shareable</res-sharing-scope></resource-ref>

The possible values for the <res-auth> element are Application andContainer. Application indicates that the enterprise bean code performsresource manager sign-on programmatically. Container indicates that thecontainer signs on to the resource manager using the principal mapping informationconfigured by the Deployer.

The <res-sharing-scope> element indicates whether connections to theresource manager obtained through the given resource manager connection factoryreference can be shared or whether the connections are unshareable. Possiblevalues are Shareable and Unshareable.

The following code sample illustrates obtaining a JDBC connection using thereference 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 providedby the Bean Provider to the actual JNDI name of the resource manager connectionfactory in the operational environment. If the value of the <res-auth> element isContainer, the Deployer is responsible for configuring the sign-on information.

The system administrator adds, removes, and configures resource managers in theEJB Server environment, and he is also in charge of giving them meaningful JNDInames.

Resource environment references

Resource Environment references are logical names that refer to administeredobjects associated with the resources. Right now, JMS destinations are the onlyadministered objects available.

The Bean Provider must declare all the references to administered objectsassociated with resources using the <resource-env-ref> elements of thedeployment descriptor. A resource environment reference is scoped to theenterprise bean whose declaration contains the <resource-env-ref> element.The Deployer binds the resource environment references to administered objects inthe target operational environment.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 94 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The EJB specification recommends, but does not require, that all resourceenvironment references be organized in the appropriate subcontext of the bean'senvironment for the resource type (for example, in the "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

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 95 of 107

descriptor element are:

• java.lang.Byte

• java.lang.Short

• 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 thetype for an environment entry value.

Please refer to section 20.2.1.2 of the EJB 2.0 specification for further details (seeResources).

Question 2:

Which of the following sub-elements of the <ejb-ref> element is optional whendefining references to other enterprise beans?

Choices:

• A. <ejb-ref-name>

• B. <ejb-ref-type>

• C. <home>

• D. <ejb-link>

• E. <remote>

Correct choice:

D

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 96 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Explanation:

The <ejb-ref> element is used for referencing an enterprise bean that is accessedthrough its remote home and remote interfaces. Its required child elements are:

• <ejb-ref-name>

• <ejb-ref-type>

• <remote>

• <home>

<ejb-link> and <description> are the optional child elements.

The <ejb-ref-name> element specifies the EJB reference name; its value is usedin the enterprise bean code. The <ejb-ref-type> element specifies the expectedtype of the enterprise bean -- session or entity. The <home> and <remote>elements specify the expected Java types of the referenced bean's home andcomponent interfaces.

The application assembler uses the optional <ejb-link> element to link an EJBreference to a target enterprise bean. The value of the <ejb-link> element mustmatch 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 (seeResources).

Summary

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

Section 15. Security management

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 97 of 107

Overview

Security management in EJB applications can be achieved in two ways:programmatically and declaratively. It is preferable to choose the declarative waybecause you can customize the security policies through the deployment descriptorwithout altering the source code of the bean. However, when instance-levelauthorization 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 tosuccessfully use an application. Security roles are mapped to real world users andgroups when the bean is deployed. Because you don't have to hard code specificuser identities into the bean code, it makes enterprise beans more portable. Youneed to use security roles whether you are using declarative or programmaticauthorization.

Programmatic security

To gain fine-grained control over security, which cannot be achieved throughdeclarative authorization, you can use programmatic access control. To do so, weneed to get the identity of the users who are invoking the bean methods.

Accessing caller informationThe javax.ejb.EJBContext interface provides two methods that allow the BeanProvider to access security information about the caller of an enterprise bean. TheBean Provider can invoke these methods only in the enterprise bean's businessmethods for which the container has a meaningful client security context:

• java.security.Principal getCallerPrincipal();: Allows theenterprise bean methods to obtain the name of the current caller principal.After authentication, the security identity of the client is represented by ajava.security.Principal object.

• boolean isCallerInRole(String roleName);: Tests whether thecurrent caller has been assigned to the given security role.

The following example shows how to use these methods:

private void modifyEmployee() {if (!ejbContext.isCallerInRole(("payroll")){throw new SecurityException(...);

}else

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 98 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

{// 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 codeThe 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 whosedeclaration contains the <security-role-ref> element.

Mapping the security rolesThe role references, which are names hard coded by the Bean Provider, need to bemapped 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 thename 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, asillustrated below:

<assembly-descriptor><security-role>

<role-name>payroll-department</role-name></security-role></assembly-descriptor>

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 99 of 107

Declarative security

The Application Assembler can restrict the access to bean methods to certainprivileged roles by defining method permissions in the deployment descriptor. Amethod permission is a permission to invoke the specified method of the enterprisebean's home and component interfaces.

In the following example, the permission to access the findByPrimaryKey()method of PayrollEJB has been granted to the security rolepayroll-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 indicateall the methods.

By specifying arguments using the <method-params> element, you can distinguishamong different overloaded methods. We can differentiate among methods havingthe same name in the home or component interface by using the <method-intf>element -- values can be Remote, Home, Local, or LocalHome. These elementsare 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>

</method></method-permission>

The Application Assembler uses the <unchecked> element instead of a role namein the <method-permission> element to indicate that a method should not bechecked for authorization. If the method permission relation specifies both the<unchecked> element for a given method and one or more security roles, themethod should not be checked for authorization.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 100 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The Application Assembler can use the <exclude-list> element to indicate theset 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 enterprisebean'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 thecaller's security context from method to method, throughout the application.

The Application Assembler uses the <security-identity> element to specifywhether the caller's security identity should be used for the execution of the beanmethods 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 thevalue as <run-as> when you want the bean to act as someone other than thecalling client.

The run-as identity is designated by one of the security roles defined by theapplication assembler in the deployment descriptor, as shown in the followingexample:

<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 itmakes calls to other enterprise beans; it does not affect the identities of its callers.

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

Responsibilities of the Deployer

The mapping of the security roles to actual users or groups in the operatingenvironment is done by the Deployer in a vendor-specific manner. Assigning thesecurity domain and principal realm to an enterprise bean application is also the

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 101 of 107

Deployer's job.

The Deployer must ensure that the assembled application is secure after it has beendeployed in the target operational environment. He also performs any tasks thathave been left unfinished by the Application Assembler.

Sample questions

Question 1:

Which of the following statements about security management of enterprise beansare 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 beanas a whole.

It is not possible to assign a run-as identity on a per-method basis. Therefore, choiceB is incorrect.

Choice C is incorrect because the deployment descriptor element used forspecifying the run-as identity is <run-as>.

Choice D is correct because the run-as identity establishes the identity theenterprise bean will use when it makes calls.

Please refer to section 21.3.4 of the EJB 2.0 specification for further details (seeResources).

Question 2:

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 102 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 Providerdeclares the role used in the code by utilizing the <security-role-ref>deployment descriptor element. Therefore, choice C is correct, while choice E isincorrect.

Choices A and D are incorrect because no such elements exist.

Choice B is incorrect because the application assembler is responsible for definingthe <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 adminsecurity role to the getAdminPassword() method in a <method-permission>element.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 103 of 107

Please refer to section 21.2.5.3 of the EJB 2.0 specification for further details (seeResources).

Summary

In this section, you learned about programmatic and declarative securitymanagement techniques. Different processes are involved, such as defining securityroles, security role references, and method permissions, which are handled by thevarious EJB roles like Bean Provider, Application Assembler, and Deployer.

We also discussed the two programmatic security control methods that are invokedon the context of the enterprise bean.

Finally, we explored the <security-identity> element that allows us to specifyalternate caller identities for the execution of bean methods.

Section 16. Wrap-up

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 theexam is assured only if you follow a focused learning approach based on the examobjectives. We hope that this tutorial helped to familiarize you with the examobjectives and the kind of questions asked.

To gain a deep understanding of the concepts, it is also necessary to get sufficienthands-on experience in all the areas covered by the exam. We recommend that youtry out the code fragments and deployment descriptor customization examplesprovided in the tutorial.

The SCBCD certification tests your competence in server-side componentdevelopment using the EJB technology. Success in this exam will definitely boostyour 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 theexam objectives and preparing you for the certification.

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 104 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Enjoy your studies and good luck with the exam!

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 105 of 107

Resources

Learn

• 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 andrelationships, Part 1, Part 2, Part 3, and Part 4 (developerWorks, March2002 -July 2002)

• EJB 2.0 CMP Tutorial

• Writing Enterprise Applications

• An introductory article on SCBCD certification by the authors of this tutorial.

• Get effective guidance and reinforce your concepts for the exam by enrolling inWhizlabs SCBCD Instructor-Led Online Training.

• Enhance your knowledge by participating in the JavaRanch SCBCD discussionforum.

• Here is a nice collection of additional resources that you must explore.

• Find more resources related to the technologies discussed here on thedeveloperWorks Java technology zone.

• Find out how you can become an IBM Certified Developer.

Get products and technologies

• Download the EJB 2.0 Specifications.

About the authors

Seema ManivannanSeema Manivannan has a Bachelor of Technology degree in Electrical and ElectronicsEngineering and a PG in Advanced Computing from C-DAC. Her work experienceincludes software development, teaching, and content development in Javaprogramming and related technologies. She holds SCJP, SCWCD, and SCBCDcertifications.

Seema has been with Whizlabs for over two years, where she has co-authored theSun certification exam simulators. She is an experienced corporate trainer and

developerWorks® ibm.com/developerWorks

Java certification success, Part 3: SCBCDPage 106 of 107 © Copyright IBM Corporation 1994, 2008. All rights reserved.

conducts instructor-led online training for the SCJP, SCWCD, and SCBCD certificationexams for Whizlabs. She is also the moderator of the Whizlabs SCBCD discussionforum.

Pradeep ChopraPradeep Chopra is the cofounder of Whizlabs Software, a global leader in IT skillassessment and certification exam preparation. A graduate of the Indian Institute ofTechnology, Delhi, Pradeep has been consulting individuals and organizations acrossthe globe on the values and benefits of IT certifications.

ibm.com/developerWorks developerWorks®

Java certification success, Part 3: SCBCD© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 107 of 107