Java Certification Success, Part 3: SCBCD

115
Java certification success, Part 3: SCBCD Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Getting started ....................................................................................... 2 2. EJB overview ......................................................................................... 4 3. Client view of a session bean .............................................................. 12 4. Session bean component contract ...................................................... 20 5. Session bean lifecycle ......................................................................... 31 6. Client view of an entity......................................................................... 38 7. Component contract for CMP .............................................................. 46 8. CMP entity bean lifecycle .................................................................... 55 9. Entity beans ......................................................................................... 63 10. EJB-QL .............................................................................................. 70 11. MDB component contract .................................................................. 77 12. Transactions ...................................................................................... 84 13. Exceptions ......................................................................................... 91 14. Enterprise bean environment ............................................................ 98 15. Security management...................................................................... 106 16. Wrap-up and resources ................................................................... 113 Java certification success, Part 3: SCBCD Page 1 of 115

Transcript of Java Certification Success, Part 3: SCBCD

Page 1: Java Certification Success, Part 3: SCBCD

Java certification success, Part 3:SCBCD

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Table of contentsIf you're viewing this document online, you can click any of the topics below to link directly to thatsection.

1. Getting started....................................................................................... 22. EJB overview......................................................................................... 43. Client view of a session bean.............................................................. 124. Session bean component contract ...................................................... 205. Session bean lifecycle ......................................................................... 316. Client view of an entity......................................................................... 387. Component contract for CMP.............................................................. 468. CMP entity bean lifecycle .................................................................... 559. Entity beans......................................................................................... 6310. EJB-QL.............................................................................................. 7011. MDB component contract .................................................................. 7712. Transactions...................................................................................... 8413. Exceptions......................................................................................... 9114. Enterprise bean environment ............................................................ 9815. Security management...................................................................... 10616. Wrap-up and resources................................................................... 113

Java certification success, Part 3: SCBCD Page 1 of 115

Page 2: Java Certification Success, Part 3: SCBCD

Section 1. Getting started

Before you start

The Sun Certified Business Component Developer (SCBCD) for the Java 2Platform, Enterprise Edition 1.3 Exam is for anyone using J2EE technologies todevelop server-side components that encapsulate the business logic of anapplication. Passing the exam demonstrates an expert level of understanding ofthe Enterprise JavaBeans (EJB) 2.0 architecture, technology features, andapplication development lifecycle.

The exam was launched worldwide on August 25, 2003. The SCBCDcertification requires you to be a Sun Certified Programmer for the Javaplatform (any edition).

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.This tutorial comprehensively covers the core concepts that are tested in theSCBCD exam; however, it is not intended to serve as an introduction to EJBtechnology. It focuses precisely on what you need to know to be successful inthe 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 securitymanagement. The tutorial is organized according to the exam objectives, witheach section dedicated to a corresponding exam objective. In addition, we'veprovided example code wherever necessary, and at the end of each section, wehave provided sample exam questions, which test the concepts discussedunder that objective. Each question includes detailed explanations about why achoice is correct or incorrect.

In every section, you must devote special attention to the responsibilities ofdifferent EJB roles, such as Bean Provider, Application Assembler, andDeployer. For the exam, you need to know which role has the primaryresponsibility for different tasks in the EJB application lifecycle.

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

Page 2 of 115 Java certification success, Part 3: SCBCD

Page 3: Java Certification Success, Part 3: SCBCD

About the authors

Seema Manivannan has a Bachelor of Technology degree in Electrical andElectronics Engineering and a PG in Advanced Computing from C-DAC. Herwork experience includes software development, teaching, and contentdevelopment in Java programming and related technologies. She holds SCJP,SCWCD, and SCBCD certifications.

Seema has been with Whizlabs for over two years, where she has co-authoredthe Sun certification exam simulators. She is an experienced corporate trainerand conducts instructor-led online training for the SCJP, SCWCD, and SCBCDcertification exams for Whizlabs. She is also the moderator of the WhizlabsSCBCD discussion forum. You can reach her at [email protected].

Pradeep Chopra is the cofounder of Whizlabs Software(http://www.whizlabs.com/) , a global leader in IT skill assessment andcertification exam preparation. A graduate of the Indian Institute of Technology,Delhi, Pradeep has been consulting individuals and organizations across theglobe on the values and benefits of IT certifications. You can reach him [email protected].

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

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

Page 4: Java Certification Success, Part 3: SCBCD

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 thedeployment descriptor itself.

Enterprise beans typically contain the business logic of enterprise applications.The EJB container provides services, such as security checks, resourcepooling, networking, thread safety, transactions, persistence, and lifecyclemanagement, thus allowing the developer to concentrate entirely on thebusiness logic.

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 datain a database. Session beans can be stateful or stateless. A stateful sessionbean retains the conversational state of the client across multiple method calls.Stateless session beans are dedicated to a client only for the duration of asingle method call. Session beans do not survive crashes of the EJB container.

Entity beans provide object representation of data in the database. They canallow shared access from multiple users. The entity, its primary key, and remotereference can 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 homeor component interfaces.

EJB 2.0

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

Page 4 of 115 Java certification success, Part 3: SCBCD

Page 5: Java Certification Success, Part 3: SCBCD

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 beans

Container generates the database access code, thus resulting in portableapplications.

° Local component and home interfaces for session and entity beans

Provides a local client view and support for efficient, lightweight access toenterprise beans from local clients.

° Home business methods for entity beans

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

° EJB Query Language (EJB-QL) for entity bean finder and selectmethods

Provides a portable, vendor-neutral way to define queries for finder andselect methods.

° Run-as security identity functionality

Allows you to specify a different principal, other than the calling client, for theexecution of the bean's methods.

° Network interoperability among EJB servers

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

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

Java certification success, Part 3: SCBCD Page 5 of 115

Page 6: Java Certification Success, Part 3: SCBCD

° 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) static fieldsis allowed.

° You must not use thread synchronization primitives to synchronize executionof multiple instances.

° You must not attempt the use of the AWT functionality to output informationto a display, or to input information from a keyboard.

° You must not attempt the use of the java.io package to access files anddirectories in the file system.

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

° A bean may act as a network client (that is, it may make use of thejava.net.Socket class), but it may not act as a network server, and thus,it must not use the java.net.ServerSocket class to accept remoteconnections.

° You must not attempt to query a class to obtain information about thedeclared members that are not otherwise accessible to the enterprise beanbecause 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.

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

Page 6 of 115 Java certification success, Part 3: SCBCD

Page 7: Java Certification Success, Part 3: SCBCD

° 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 a particularcode source.

° You must not attempt to load a native library.

° You must not attempt to gain access to packages and classes that the usualrules of the Java programming language make unavailable to the enterprisebean.

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

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

° You must not attempt to use the subclass and object substitution features ofthe 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:

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

Java certification success, Part 3: SCBCD Page 7 of 115

Page 8: Java Certification Success, Part 3: SCBCD

° 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 codesthe Java classes that implement the enterprise bean's businessmethods, the bean's home, and component interfaces. The deliverablesare ejb-jar files (that include one or more beans and an XMLdeployment descriptor).

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

DeployerTakes one or more ejb-jar files produced by a Bean Provider orApplication Assembler and deploys them in a specific EJB container.The Deployer delivers enterprise beans that have been customized forthe target operational environment. To perform their role, the Deployersuse tools provided by the EJB 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 SystemAdministrator to 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 anOS vendor, middleware vendor, or database vendor. The current EJBarchitecture assumes that the EJB Server Provider and the EJBContainer Provider roles are the same vendor.

System Administrator

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

Page 8 of 115 Java certification success, Part 3: SCBCD

Page 9: Java Certification Success, Part 3: SCBCD

Responsible for the configuration and administration of the enterprise'scomputing and networking infrastructure that includes the EJB serverand container. It also oversees the well being of the deployed enterprisebean applications at runtime.

Requirements for an ejb-jar file

The ejb-jar file is the standard format for the packaging of enterprise beans.

The ejb-jar file must contain, either by inclusion or by reference, the class filesof each enterprise bean as follows:

° The enterprise bean class° The enterprise bean home and component interfaces (not for MDBs)° The primary key class, if the bean is an entity bean

The ejb-jar file must contain the deployment descriptor, stored with the 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 thateach enterprise bean class and the home and component interfaces dependupon, except J2EE 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 aregenerated by the container and hence are not included in the ejb-jar file.

Sample questions

Question 1:

Which of the following must not be packaged in the ejb-jar file of an entity bean?

Choices:

° A. The primary key class of the bean° B. Classes used as method return types° C. Exception classes° D. Stub of the EJB Object° E. Classes used as method arguments

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

Java certification success, Part 3: SCBCD Page 9 of 115

Page 10: Java Certification Success, Part 3: SCBCD

Correct choice:

D

Explanation:

The ejb-jar file is the standard format for packaging enterprise beans andassembled applications. It contains the XML deployment descriptor, theenterprise bean classes, the enterprise bean remote and home interfaces, andthe primary key class (only for entity beans). The ejb-jar should also contain thesuperclasses and superinterfaces of the above classes. It should also includethe dependent classes and the classes and interfaces used as methodparameters, return types, and exceptions. So choices A, B, C, and E areincorrect.

To learn more about the ejb-jar file, refer to section 23 of the EJB 2.0specification (see Resources on page113 ).

Question 2:

Which of the following are not allowed in enterprise beans according to the EJB2.0 programming restrictions?

Choices:

° A. Extending from a class° B. Creating client sockets° C. Having read/write static fields° D. Loading native libraries° E. Managing threads

Correct choice:

C, D, and E

Explanation:

The Bean Provider must follow some programming restrictions to ensure thatthe enterprise bean is portable and can be deployed in all EJB 2.0 containers.An enterprise bean must not use read/write static fields, however static fieldsare allowed if they are made read-only by declaring them with the finalkeyword. The bean must not attempt to load a native library; this restriction is toavoid security holes. The enterprise bean must not manage threads or threadgroups because these functions are reserved for the EJB container.

Choice A is incorrect because Java inheritance is allowed for enterprise bean

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

Page 10 of 115 Java certification success, Part 3: SCBCD

Page 11: Java Certification Success, Part 3: SCBCD

classes. Choice B is incorrect because the EJB architecture allows anenterprise bean instance to be a network client. However, it does not allow it tobe a network server.

For a complete list of the EJB 2.0 programming restrictions, please refer tosection 24.1.2 of the EJB 2.0 specification (see Resources on page113 ).

Summary

This section provided an overview of the EJB architecture and the differenttypes of enterprise beans. We discussed which features and APIs areguaranteed to be supported by the EJB 2.0 specification, and you now know theprogramming restrictions on EJB business methods to ensure that the bean isportable and can be deployed in any compliant EJB 2.0 container. Theresponsibilities of the different roles involved in the EJB development lifecycleare spread over the remaining objectives. In this objective, we have simplyprovided an overall picture of the responsibilities of each role.

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

Java certification success, Part 3: SCBCD Page 11 of 115

Page 12: Java Certification Success, Part 3: SCBCD

Section 3. Client view of a session bean

Local and remote clients

A session bean can use its component interface to expose its businessmethods to clients. The Java object that implements the component interface iscalled the EJB Object of the bean. To invoke a business method on a sessionbean, the client needs to get a reference to the bean's EJB Object. The clientobtains a reference to the EJB Object by calling a method on the home object ofthe bean. The home object is a Java object that implements the home interfaceof the bean.

A local client of a session bean is collocated in the same JVM as the bean.Here, the local component and home interfaces provide the client view. Thelocal client view is not location-independent. The arguments and results of themethods of the local interface and local home interface are passed byreference.

A remote client of a session bean can be another enterprise bean deployed inthe same or different container; or it can be an arbitrary Java program, such asan application, applet, or servlet. It can even be a non-Java program, such as aCORBA client. Here the remote component and home interfaces provide theclient view. The remote client view of a session bean is location-independent.The arguments and results of the methods of the remote interface and remotehome interface are passed 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 contextfor performing JNDI naming operations. The lookup method takes the bean'sJNDI name as the argument:

Context initialContext = newInitialContext();

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

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

Page 12 of 115 Java certification success, Part 3: SCBCD

Page 13: Java Certification Success, Part 3: SCBCD

CartHome.class);

When looking up the remote home object, thePortableRemoteObject.narrow() method must be used on the objectreturned from the JNDI lookup, rather than using simple Java language casts.This method is required because the remote home stub, which is obtained fromthe JNDI lookup, is RMI-IIOP compatible and needs to be converted into a Javaobject that actually implements the home interface.

In the case of local clients, the return value of theInitialContext.lookup() method can be directly cast to the local homeinterface because the object returned is 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.EJBHomeinterface.

The remote home interface allows a client to:

° Create a new session object° Remove a session object° Get the EJBMetaData interface for the session bean° Obtain a handle for the remote home interface

Creating a new session object

The home interface of a stateful session bean defines one or morecreate<METHOD>(...) methods to create a session object. The return typeof a create<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)

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

Java certification success, Part 3: SCBCD Page 13 of 115

Page 14: Java Certification Success, Part 3: SCBCD

throws RemoteException, CreateException;

}

The home interface of a stateless session bean defines only one createmethod, which does not take any arguments.

Removing a session object

The EJBHome interface defines two remove() methods:

° void remove(Handle handle)

° void remove(java.lang.Object primaryKey)

A session bean can be removed by invoking the first remove() method,passing the Handle as the argument. As session beans do not have primarykeys, invoking the remove(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 EJBMetaData

The EJBMetaData interface allows the client to obtain class information aboutthe enterprise 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 handle

The home handle is a serializable object that can be used at a later time tore-obtain a reference to the remote home object, possibly in a different JVM.

The getHomeHandle() method of EJBHome can be called to obtain thefollowing:

public HomeHandle getHomeHandle()

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

Page 14 of 115 Java certification success, Part 3: SCBCD

Page 15: Java Certification Success, Part 3: SCBCD

Local home interface

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

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 localclients because there aren't any stubs.

Component interface

The component interface exposes the business methods of the session objectto clients. The EJB Object, which implements this interface, delegatesinvocation of a business method to the session bean instance.

The remote component interface extends the javax.ejb.EJBObjectinterface. 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.EJBLocalObjectinterface are:

° EJBLocalHome getEJBLocalHome()

° java.lang.Object getPrimaryKey()

° boolean isIdentical(EJBLocalObject obj)

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

Java certification success, Part 3: SCBCD Page 15 of 115

Page 16: Java Certification Success, Part 3: SCBCD

° void remove()

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

Getting the home object reference

If the reference to the EJB Object is available, we can get a reference to thebean's home object using the getEJBHome() method for remote clients andgetEJBLocalHome() for local clients. This method of obtaining the homeobject reference is more efficient than performing a JNDI lookup to locate thehome.

Getting the handle

A handle is a serializable object that abstracts a network reference to an EJBObject. The Handle interface is implemented by all the EJB object handles.The client can serialize the Handle object at any time and deserialize it later toobtain a reference to the original EJB object. The EJBObject.getHandle()method returns a Handle object. Because local clients do not need handles,the EJBLocalObject interface does not define a similar method.

Removing the bean

The remove method in the EJBObject and EJBLocalObject interfaces canbe used to remove the EJB Object. It tells the container to free up anyresources held for the bean.

Comparing session objects

The 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 uniqueidentity because they hold the client conversational state. So two stateful

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

Page 16 of 115 Java certification success, Part 3: SCBCD

Page 17: Java Certification Success, Part 3: SCBCD

session bean instances created from the same home are not consideredidentical. For example:

MyStatefulBean myStatefulBean1 = myStatefulBeanHome.create(...);MyStatefulBean myStatefulBean2 = myStatefulBeanHome.create(...);if (myStatefulBean1.isIdentical(myStatefulBean1)) {

// this test must return true}if (myStatefulBean1.isIdentical(myStatefulBean2)) {

// this test must return false}

Sample questions

Question 1

What do remote and local component interfaces of session beans have incommon?

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 thelocal and remote home interfaces of the session bean, respectively.

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

Java certification success, Part 3: SCBCD Page 17 of 115

Page 18: Java Certification Success, Part 3: SCBCD

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

Choice E is incorrect because session beans do not make their identityavailable to clients. As a result, when the getPrimaryKey() method isinvoked on the local and remote component interfaces, ajavax.ejb.EJBException and java.rmi.RemoteException will bethrown respectively to the client.

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

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 wewant to test remote component interfaces, we consider the former one, whichdefines the isIdentical() method as follows:

public boolean isIdentical(EJBObject other);

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

Summary

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

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

Page 19: Java Certification Success, Part 3: SCBCD

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

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

Java certification success, Part 3: SCBCD Page 19 of 115

Page 20: Java Certification Success, Part 3: SCBCD

Section 4. Session bean component contract

Overview of session beans

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

Stateful session beans retain the conversational state of the client, whileStateless session beans are dedicated to a client only for the duration of themethod call. Stateless session beans can have instance variables, but theycannot preserve client data across multiple method invocations. All instances ofa particular type of stateless session bean are equivalent, so the container maychoose any available instance to serve a client method call. Two successiveclient calls to a stateless session bean may be served by two different instancesof that session bean.

All session beans must implement the javax.ejb.SessionBean interface.The container uses the SessionBean() methods to notify lifecycle events tothe enterprise 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 instanceafter its construction. The SessionContext reference may be stored in aninstance field of the session bean for future use.

The ejbPassivate() notification signals the intent of the container topassivate the instance.

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

The ejbRemove() notification signals that the instance is in the process ofbeing removed by the container.

The ejbPassivate() and ejbActivate() methods are invoked only in thelife of stateful beans and not for stateless session beans. The reason is thatstateless session beans do not need to persist the client state. All the instancesof a particular type of a stateless session bean are equivalent, and the sameinstance may be reused to serve multiple clients. Even though stateless beans

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

Page 20 of 115 Java certification success, Part 3: SCBCD

Page 21: Java Certification Success, Part 3: SCBCD

are never passivated, we need to define the ejbActivate() andejbPassivate() callback methods in the bean class because the classimplements the SessionBean interface. For example:

public class HelloBean implements SessionBean {private SessionContext sessionContext;public void ejbCreate() { }public void ejbRemove() { }public void ejbActivate() { }public void ejbPassivate() { }public void setSessionContext(SessionContext sessionContext) {this.sessionContext = sessionContext;}

public String sayHello() {return "Hello World!!!!!";}

}

A client creates a session bean instance using one of the create <METHOD>()methods defined in the session bean's home interface. The container calls 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 haveonly one ejbCreate() method, which must not take any arguments.

// Home interface

public interface HelloHome extends EJBHome {public HelloObject create() throws RemoteException, CreateException;

}

// Remote interface

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

}

Passivation of a stateful session bean

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

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

Java certification success, Part 3: SCBCD Page 21 of 115

Page 22: Java Certification Success, Part 3: SCBCD

Responsibilities of the bean provider

All 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 ofonly primitive values, serializable objects, null, and the following special types:

° An enterprise bean's remote interface reference° An enterprise bean's remote home interface reference° An entity bean's local interface reference° An entity bean's local home interface reference° A reference to the SessionContext object° A reference to the environment naming context (java:comp/env JNDI

context)° A reference to the UserTransaction interface° A reference to a resource manager connection factory° An object that is not directly serializable, but becomes serializable by

replacing the references to the special types mentioned above 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° UserTransaction interface

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

Responsibilities of the container

The container performs Java serialization (or its equivalent) to passivate thebean instance. A stateful session bean may not be passivated while it isparticipating in a transaction. The container must be able to properly save andrestore the special types mentioned in the previous section, even though theyare not serializable. A session bean instance may be destroyed if the instancedoes not meet the passivation requirements.

SessionContext interface

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

Page 22 of 115 Java certification success, Part 3: SCBCD

Page 23: Java Certification Success, Part 3: SCBCD

The SessionContext interface represents the bean's context maintained bythe container. A reference to the SessionContext object is passed to thebean when the container invokes the setSessionContext() callbackmethod.

The methods defined in this interface are as follows:

° getEJBObject(): Returns the session bean's remote interface.

° getEJBHome(): Returns the session bean's remote home interface.

° getEJBLocalObject(): Returns the session bean's local interface.

° getEJBLocalHome(): Returns the session bean's local home interface.

° getCallerPrincipal(): Returns the java.security.Principal thatidentifies the invoker of the bean instance's EJB Object.

° isCallerInRole(): Tests whether the session bean instance's caller hasa particular role.

° setRollbackOnly(): Allows the instance to mark the current transactionfor a rollback. It is only for session beans with container-managedtransaction (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 sessionbeans with bean-managed transaction (BMT) demarcation.

SessionSynchronization interface

A stateful session bean with CMT demarcation may implement thejavax.ejb.SessionSynchronization interface to receive notificationswhen a transaction starts, when it is about to end, and when it is over. Thesenotifications are helpful for the bean to perform database synchronizationoperations.

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

Java certification success, Part 3: SCBCD Page 23 of 115

Page 24: Java Certification Success, Part 3: SCBCD

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 about tobe committed. This method is not invoked if the transaction is marked forrollback.

° afterCompletion(boolean flag): Notifies the instance that the currenttransaction has completed. The flag is true if the transaction has beencommitted 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 notallowed to maintain transactions across multiple methods, so they must notimplement this interface.

Responsibilities of the Bean Provider

The Bean Provider is responsible for delivering the following files:

° Session bean class

° Session bean's remote interface and remote home interface, if the sessionbean provides a remote client view

° Session bean's local interface and local home interface, if the session beanprovides a local client view

The classes must follow certain programming guidelines as specified below.

Session bean class° It must implement the javax.ejb.SessionBean interface.

° It must be defined as publi, must not be final or abstract.

° It must have a public constructor that takes no parameters.

° It must not define the finalize() method.

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

Page 24 of 115 Java certification success, Part 3: SCBCD

Page 25: Java Certification Success, Part 3: SCBCD

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

ejbCreate<METHOD>(...) methods in the case of stateful session beans,and no more than one no-argument ejbCreate() method in the case ofstateless 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 the ejbCreate(...)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 sessionbean's remote interface.

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

Java certification success, Part 3: SCBCD Page 25 of 115

Page 26: Java Certification Success, Part 3: SCBCD

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

interface 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 matching methodin the session bean's class.

° All the exceptions defined in the throws clause of the matching method ofthe session bean class must be defined in the throws clause of the methodof the interface.

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

° The remote interface methods must define java.rmi.RemoteExceptionin the throws clause, while the local interface methods must not.

Home interface° The remote home interface must extend the EJBHome interface and the local

home interface must extend the EJBLocalHome interface.

° The home interface is allowed to have superinterfaces.

° The home interface must define one or more create<METHOD>(...)methods. A stateless session bean must define exactly one create()method with no arguments.

° Each create() method must be named create<METHOD>, and it 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() and

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

Page 26 of 115 Java certification success, Part 3: SCBCD

Page 27: Java Certification Success, Part 3: SCBCD

ejbCreate().

° The return type for a create<METHOD>() method must be the sessionbean's component interface type.

° The remote home interface methods must definejava.rmi.RemoteException in the throws clause, while the local homeinterface 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 thegeneration of the following classes:

° A class that implements the session bean's remote home interface° A class that implements the session bean's remote interface° A class that implements the session bean's local home interface° A class that implements the session bean's local interface° The handle classes for the session bean's remote home and remote

interfaces° A class that implements the EJBMetaData interface and provides metadata

to the remote client view contract.

The container must ensure that only one thread is executing an instance at anytime. If a client request arrives for an instance while the instance is executinganother request, the container may throw java.rmi.RemoteException tothe second request if the client is a remote client, orjavax.ejb.EJBException if the client is a local client.

Sample questions

Question 1:

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

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

Java certification success, Part 3: SCBCD Page 27 of 115

Page 28: Java Certification Success, Part 3: SCBCD

Choices:

° A. public void ejbCreate(String name) throwsCreateException {}

° 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 thatmust be prefixed with ejbCreate. Moreover, the method declaration must bepublic, it must neither contain the final nor static modifiers, its arguments mustbe legal RMI-IIOP types, the return type must be void (session beans hide theiridentity, which is the main difference between them and entity beans!), and itsthrows clause must contain the javax.ejb.CreateException as well asarbitrary application exceptions. 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 homeinterface.

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 mustnot take any arguments. The other rules mentioned above still apply.

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

Question 2:

Which of the following are defined by the javax.ejb.SessionBeaninterface?

Choices:

° A. A setSessionContext() method that takes an argument of the typejavax.ejb.EJBContext

° B. An unsetSessionContext() method° C. Three methods that have the same signature as methods defined in the

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

Page 28 of 115 Java certification success, Part 3: SCBCD

Page 29: Java Certification Success, Part 3: SCBCD

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 interfacedoes define 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 doesnot declare any method called unsetSessionContext(). It is worth notingthat only the javax.ejb.EntityBean interface defines a method forunsetting the context of 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 ofa method.

From the above explanation, it follows that choice D is also correct.

Choice E is incorrect because the ability to create new session beans isprovided through the local or remote home interface.

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

Summary

Thi section briefly covered the differences between stateful and statelesssession beans. We identified the methods defined in the SessionBean andSessionContext interfaces. The significance of the

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

Java certification success, Part 3: SCBCD Page 29 of 115

Page 30: Java Certification Success, Part 3: SCBCD

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

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

Page 30 of 115 Java certification success, Part 3: SCBCD

Page 31: Java Certification Success, Part 3: SCBCD

Section 5. Session bean lifecycle

Stateful session beans

The lifetime of a stateful session bean instance is controlled by the client. Thebean contains 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 thecreate() method on the home of the bean. The container instantiates thebean and invokes the setSessionContext() method, passing aSessionContext instance. The bean is assigned to its EJB Object. Thecontainer invokes the ejbCreate() method matching the create() methodinvoked by the client. The reference to the EJB Object is returned to the client;now the bean is in the Ready state.

The container might choose to passivate an inactive bean instance to conserveresources. When the bean is about to be passivated, the ejbPassivate()method is invoked. A session bean cannot be passivated while it is in atransaction. If a client invokes a session object whose session bean instancehas been passivated, the container will activate the instance. To this end, thecontainer invokes ejbActivate() on the bean after successfully restoring itfrom 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.

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

Java certification success, Part 3: SCBCD Page 31 of 115

Page 32: Java Certification Success, Part 3: SCBCD

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 ismuch simpler as compared to that of a stateful session bean. The container caninstantiate the stateless session bean at any time, it is not related to the client'sinvocation of the create() method. The stateless session bean is notpassivated or activated, because it does not maintain any client state.

After instantiation, the container invokes setSessionContext() followed byejbCreate(), and the bean is ready to serve client requests. When a clientinvokes the create() method on the home interface of a stateless sessionbean, an EJB Object is created for the bean and returned to the client. Thecontainer selects one of its method-ready instances and ties it to the client'sEJB Object, only when the client calls a business method.

After serving the client, the bean is disassociated from the EJB Object andreturns to the Ready state. When the container no longer needs the instance,the container invokes ejbRemove() on it.

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

Page 32 of 115 Java certification success, Part 3: SCBCD

Page 33: Java Certification Success, Part 3: SCBCD

Operations allowed in the methods of a statefulsession bean

° getEJBObject() and getEJBLocalObject() of SessionContext

Can be invoked from all the methods except setSessionContext() andthe constructor because there is no session object identity available in thosemethods.

° getCallerPrincipal() and isCallerInRole() of SessionContext

Can be invoked from all the methods except setSessionContext() andthe constructor because there is no client security context available in thosemethods.

° getRollbackOnly() and setRollbackOnly() of SessionContext

Can be invoked only from the afterBegin() and beforeCompletion()business methods because there is no meaningful transaction contextavailable in other methods. Moreover, only beans with CMT demarcationcan invoke these methods.

° getUserTransaction() of SessionContext methods ofUserTransaction

Can be invoked from the ejbCreate(), ejbRemove(), ejbActivate(),and ejbPassivate() business methods of beans with BMT demarcation.

° Accessing resource managers and enterprise beans

Not allowed in the session bean methods for which the container does nothave a meaningful transaction context or client security context. So they canbe called in every method except setSessionContext() andafterCompletion().

° getEJBHome() and getEJBLocalHome() of SessionContext, JNDIaccess to java:comp/env

Allowed in all methods except the constructor.

Operations allowed in the methods of a statelesssession bean

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

Java certification success, Part 3: SCBCD Page 33 of 115

Page 34: Java Certification Success, Part 3: SCBCD

° getEJBObject() and getEJBLocalObject() of SessionContext

Can be invoked from all the methods except setSessionContext() andthe constructor because there is no session object identity available in thosemethods.

° getCallerPrincipal() and isCallerInRole() of SessionContext

Can be invoked from business methods only because there is no clientsecurity context available in other methods.

° getRollbackOnly() and setRollbackOnly() of SessionContext

Can be invoked only from business methods because there is no meaningfultransaction context available in other methods. Only beans with CMTdemarcation can invoke these methods.

° getUserTransaction() of SessionContext

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

° Methods of UserTransaction

Can be invoked only from business methods of beans with BMTdemarcation.

° Accessing resource managers and enterprise beans

Not allowed in the session bean methods for which the container does nothave a meaningful transaction context or client security context. So they canbe called only from business methods.

° getEJBHome() and getEJBLocalHome() of SessionContext, JNDIaccess to java:comp/env

Allowed in all the methods except the constructor.

Sample questions

Question 1:

Which of the following events will result in a stateful session bean transiting tothe Does-not-exist state?

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

Page 34 of 115 Java certification success, Part 3: SCBCD

Page 35: Java Certification Success, Part 3: SCBCD

Choices:

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

security credentials.° E. The client invokes remove() on the component interface of the bean.

Correct choice:

A, D, and E

Explanation:

Three ways exist for making a stateful session beans transit to theDoes-not-exist state. When either the bean is in the Ready state and a timeoutoccurs (choice A) or the client invokes remove() on the component interfaceof the bean (choice E), the EJB container invokes ejbRemove() on the beaninstance, which makes it transit to the Does-not-exist state.

Choice B is incorrect because when the EJB container passivates the beaninstance -- that is, it invokes the ejbPassivate() method on it -- the beangoes from the method-ready state to the Passive state.

Choice C is incorrect because it is the container's job to invoke ejbRemove()on the bean instance. The client doesn't have access to this method.

Choice D is correct because if a client invokes a method for which the accesshas been 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 besystem exceptions. When a system exception is thrown from any method of thebean regardless of its current state, the bean goes to the Does-not-exist state.

Please refer to sections 7.6 and 21.6.9 of the EJB 2.0 specification for furtherdetails (see Resources on page113 ).

Question 2:

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

Choices:

° A. Invoke getPrimaryKey() on the SessionContext object

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

Java certification success, Part 3: SCBCD Page 35 of 115

Page 36: Java Certification Success, Part 3: SCBCD

° 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 sessionbean with a CMT demarcation because it defines the afterCompletion()method of the javax.ejb.SessionSynchronization interface. BMTsession beans and stateless session beans are not allowed to implement thatinterface.

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

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

Choice C is incorrect because the question states that the session bean definesa remote client view. As a result, it is not allowed to invokegetEJBLocalHome() on the SessionContext object. AnIllegalStateException is thrown by the container if it does.

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

Choice E is correct because the bean is allowed to perform JNDI lookups fromany instance method of the session bean class, except from constructors.

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

Summary

This section addressed the details of stateless and stateful session beanlifecycles. You must be able to arrange the various lifecycle events in the properorder. Because stateless session beans do not maintain client state, theirlifetime is not controlled by the client, which makes the event flow different from

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

Page 36 of 115 Java certification success, Part 3: SCBCD

Page 37: Java Certification Success, Part 3: SCBCD

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

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

Java certification success, Part 3: SCBCD Page 37 of 115

Page 38: Java Certification Success, Part 3: SCBCD

Section 6. Client view of an entity

Overview

Entity beans allow their clients to access and manipulate data from a databasein an object-oriented manner. Multiple clients may access an entity objectconcurrently. It is the responsibility of the container to synchronize the accessby means of transactions.

An entity bean may provide a remote client view, a local client view, or both.While the remote client view is location dependent, the local client view is not.However, to be the target of container-managed relationships (CMRs), entitybeans need to provide local interfaces.

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

Home interface

The home interface allows the client to create, find, and remove entity objectswithin the enterprise bean's home as well as to execute home businessmethods, which are not specific to a particular entity bean. For each entity beandeployed in a container, the container provides a class that implements a homeinterface for the entity bean.

The following code illustrates the definition of the remote home interface of anentity bean.

public interface EmployeeHome extends EJBHome {public Employee create () throws RemoteException, CreateException;public Employee findByPrimaryKey(String name) throws RemoteException, FinderException;public Employee createWithDetails (Integer SSN, String name) throws RemoteException,

CreateException;}

The remote home interface extends the javax.ejb.EJBHome interface.

Methods provided by EJBHome are as follows:

° EJBMetaData getEJBMetaData()

° HomeHandle getHomeHandle()

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

Page 38 of 115 Java certification success, Part 3: SCBCD

Page 39: Java Certification Success, Part 3: SCBCD

° 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 notthrow RemoteException.

The method provided by EJBLocalHome is voidremove(java.lang.Object primaryKey).

Creating entity objects

The create methods are used for creating new entities, which results in insertionof new rows in the database. For entity beans, create methods are optional inthe home interface. Typically, they take arguments, though it's not mandatory.In addition:

° There can be zero or more create methods.

° They must start with the prefix create.

° They have to match the ejbCreate() and ejbPostCreate() 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:

Context initialContext = new InitialContext();EmployeeHome empHome = (EmployeeHome)javax.rmi.PortableRemoteObject.narrow(

initialContext.lookup("java:comp/env/ejb/emp"), EmployeeHome.class);EmployeeRemote emp = empHome.createWithDetails(new Integer(3),"John"));

Finding entity objects

An entity bean client needs to work with existing data more frequently thancreating new entities. Multiple finder methods can be defined in the homeinterface for the purpose of obtaining references to existing entities. In addition:

° There can be one or more finder methods.

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

Java certification success, Part 3: SCBCD Page 39 of 115

Page 40: Java Certification Success, Part 3: SCBCD

° The method name must start with the prefix find.

° The throws clause contains javax.ejb.FinderException.java.rmi.RemoteException is required if the home interface is remote.

° The return type must be the bean's component interface or a 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's primarykey type. This method cannot be overloaded.

° Every finder method in the home must have a matching method in the beanclass that starts with the prefix ejbFind.

The following code illustrates multiple finder methods defined in the remotehome interface of an entity bean.

public interface AccountHome extends javax.ejb.EJBHome{

public Account findByPrimaryKey(String accountNumber) throws RemoteException,FinderException;

public Collection findByLastName (String lastName) throws RemoteException,FinderException;

public Collection findByFirstName (String firstName) throwsRemoteException, FinderException;}

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

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

Removing entity objects

The home interface provides two methods to remove entity objects.

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

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

Page 40 of 115 Java certification success, Part 3: SCBCD

Page 41: Java Certification Success, Part 3: SCBCD

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

Home business methods

Home business methods contain business logic that is not specific to an entitybean instance. They are ideal for batch operations. In addition:

° Their names must not start with "create," "find," or "remove."

° If the home is remote, the throws clause must include thejava.rmi.RemoteException. Also, the arguments and return types mustbe 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 componentinterface, which defines the business methods callable by clients. An entitybean's remote component interface must extend the javax.ejb.EJBObjectinterface, and the local component interface must extend thejavax.ejb.EJBLocalObject interface. These interfaces define the methodsthat allow the client to perform some useful operations on an entity object'sreference. The implementation for these methods is provided by the container.

Getting the home object reference

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

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

Java certification success, Part 3: SCBCD Page 41 of 115

Page 42: Java Certification Success, Part 3: SCBCD

Getting the entity bean handle

An entity object's handle is a serializable object that identifies the entity objecton a network. A remote client can obtain the entity object's handle by invokingthe getHandle() method on the remote component interface. ThegetHandle() method is only available on the remote component interface andnot on the local one.

Getting the primary key of the entity

Every entity object has a unique identity within its home, which is denoted by itsprimary key. A client can determine the entity object's identity within its home byinvoking the getPrimaryKey() method on the component interface. If anentity object has both a remote home interface and a local home interface, theresult of invoking the getPrimaryKey() method on a reference to the entityobject's remote interface and on a reference to the entity object's local interfaceis the same.

Comparing entity objects

A client can test whether two entity object references refer to the same entityobject by using the isIdentical() method. Alternatively, if a client obtainstwo entity object references from the same home, it can determine if they referto the same entity 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 by localclients

Removing entity objects

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

Sample questions

Question 1:

Which of the following statements about the EJBLocalObject interface of anentity bean are true?

Choices:

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

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

Page 42 of 115 Java certification success, Part 3: SCBCD

Page 43: Java Certification Success, Part 3: SCBCD

° 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 interfaceand local home interface. The EJBLocalObject interface does not define agetHandle() method because the client and the enterprise bean are locatedin the same EJB container. The Handle is a serializable reference, which allowsa remote client to obtain a reference to an enterprise bean on a remote node ona network. Therefore, it is not necessary to get the Handle object in this case.

The EJBLocalObject interface does define methods to get the primary keyand to compare two local EJB Objects. So choices B and C are incorrect.

The EJBLocalObject() methods do not throw a RemoteExceptionbecause this interface is used for co-located beans in the same JVM. However,they throw EJBException when some kind of container or transaction errorhappens. 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 on page113 ).

Question 2:

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

public interface CarHome extends javax.ejb.EJBHome

{

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

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

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

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

Java certification success, Part 3: SCBCD Page 43 of 115

Page 44: Java Certification Success, Part 3: SCBCD

...

}

Based on the above code, select all the correct statements.

Choices:

° A. The CarHome interface is a local home interface.

° B. The return type of each create() method (that is, Car) must be the typeof the local component interface.

° C. The return type of each create() method (that is, Car) must be the typeof 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 create methods.

° 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. Inorder for 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 componentinterface. Therefore, choice C is correct.

Choice D is incorrect because nothing prevents create methods from declaringapplication exceptions in their throws clause. Such exceptions are thrown ifsome problem occurs during the bean creation process.

It is perfectly admissible for home interfaces of entity beans to declareoverloaded create methods. This would also be allowed for stateful session

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

Page 44 of 115 Java certification success, Part 3: SCBCD

Page 45: Java Certification Success, Part 3: SCBCD

beans, but not for stateless session beans, which must declare only onecreate() method that is named "create" and that takes no arguments.Therefore, choice E is correct while choice F is incorrect.

Please refer to sections 9.5 and 9.6 of the EJB 2.0 specification for furtherdetails (see Resources on page113 ).

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 componentinterfaces and 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 forremote clients while primary keys can be retrieved by both remote and localclients.

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

Java certification success, Part 3: SCBCD Page 45 of 115

Page 46: Java Certification Success, Part 3: SCBCD

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 andits persistent representation, leading to data independence and bean portability.CMP also allows multiple entity beans to have CMRs among themselves.

The Bean Provider uses the deployment descriptor to specify the CMP fieldsand CMR fields. The set of XML elements in the deployment descriptordescribing the CMP and CMR fields is known as the abstract persistenceschema of the entity bean. The Deployer maps the abstract persistence schemaof a set of interrelated entity bean classes into the physical schema used by theunderlying data store by using the container provider's tools.

CMP entity bean programming contract

Follow these guidelines when developing a CMP entity bean:

° The entity bean class must be abstract.

° Container-managed fields must not be defined in the bean class.

° The CMP and CMR fields must be specified in the deployment descriptorusing the <cmp-field> and <cmr-field> elements respectively.

° Accessor methods must be defined in the bean class for the CMP and CMRfields.

° Accessor methods must be public and abstract, named with the first letter ofthe name of the CMP or CMR fields in uppercase, and prefixed by get orset.

° The accessor methods for a CMR field must be defined in terms of the localinterface of the related entity bean.

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

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

Page 46 of 115 Java certification success, Part 3: SCBCD

Page 47: Java Certification Success, Part 3: SCBCD

° The accessor methods for one-to-many or many-to-many relationships mustutilize the java.util.Collection or java.util.Set interfaces.

° 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();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 wehave defined abstract accessor methods for the container-managed fields,which map to actual database columns. The fields need to be specified in thedeployment descriptor using <cmp-field> elements, as shown below:

...<entity>

<ejb-name>CourseBean</ejb-name><local-home>CourseHome</local-home><local>Course</local><ejb-class>example.cmp.basic.CourseBean</ejb-class><prim-key-class>String</prim-key-class><primkey-field>courseId</primkey-field><persistence-type>Container</persistence-type><cmp-version>2.x</cmp-version><reentrant>False</reentrant><cmp-field>

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

Java certification success, Part 3: SCBCD Page 47 of 115

Page 48: Java Certification Success, Part 3: SCBCD

<field-name>courseId</field-name></cmp-field><cmp-field>

<field-name>trainer</field-name></cmp-field>

</entity>...

CMP relationships

CMRs are defined in terms of the local interfaces of the related entity beans.Relationships may be one-to-one, one-to-many, or many-to-many relationships,and may be either bi-directional or unidirectional. An entity bean that does nothave a local interface can have only unidirectional relationships from itself to theother entity beans.

The relationships are defined in the <relationships> section of thedeployment descriptor.

Within the <relationships> element, each entity-to-entity relationship isdefined in a separate <ejb-relation> element, as illustrated below. HereEmployeeEJB and AddressEJB share a one-to-one unidirectional relationship:

<ejb-relation><ejb-relationship-role>

<ejb-relationship-role-name>Employee</ejb-relationship-role-name><multiplicity>One</multiplicity>

<relationship-role-source><ejb-name>EmployeeEJB</ejb-name>

</relationship-role-source><cmr-field>

<cmr-field-name>address</cmr-field-name></cmr-field>

</ejb-relationship-role><ejb-relationship-role>

<ejb-relationship-role-name>Address</ejb-relationship-role-name><multiplicity>One</multiplicity><relationship-role-source>

<ejb-name>AddressEJB</ejb-name></relationship-role-source>

</ejb-relationship-role></ejb-relation>

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

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

Page 48 of 115 Java certification success, Part 3: SCBCD

Page 49: Java Certification Success, Part 3: SCBCD

contained in the <relationship-role-source> element. The<multiplicity> element describes the multiplicity of the role that participatesin a relation (One or Many).

If one bean maintains a relationship to another bean, the reference is declaredusing a <cmr-field> element. A CMR field can use only the local interface ofthe referenced bean. For every <cmr-field> element, there must be a pair ofabstract accessor methods in the bean class, as shown below. The name of theaccessor method is determined by the name of the relationship field in thedeployment descriptor.

public abstract class EmployeeBean implements EntityBean {public abstract void setAddress(AddressLocal address);public abstract AddressLocal getAddress();

}

Assigning relationships

When we reassign relationships, the container ensures that data integrity ismaintained by using the multiplicity defined for both beans. Consider thefollowing relationships between instances of Employee and Address entitybeans.

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:

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

Java certification success, Part 3: SCBCD Page 49 of 115

Page 50: Java Certification Success, Part 3: SCBCD

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

Now consider the relationships between different instances of the Departmentbean and the Employee bean. The multiplicity for Employee is "Many" and forDepartment is "One."

Now let us make the assignmentemployeeC.setDepartment(employeeA.getDepartment()); , asshown below:

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

Page 50 of 115 Java certification success, Part 3: SCBCD

Page 51: Java Certification Success, Part 3: SCBCD

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,if the <cascade-delete> element is specified for the target bean. The entitythat uses the <cascade-delete> element must have a multiplicity of "One" inthe relationship. The container calls the ejbRemove() method on the targetbean instance due to the cascade delete operation and then removes its datafrom the database.

Consider the relationship between an employee and his profile. Because<cascade-delete> has been specified for the ProfileEJB bean, removal ofthe EmployeeEJB bean instance will cause the container to automaticallydelete the associated Profile instance also:

<ejb-relation><ejb-relationship-role>

<ejb-relationship-role-name>Employee</ejb-relationship-role-name><multiplicity>One</multiplicity>

<relationship-role-source><ejb-name>EmployeeEJB</ejb-name>

</relationship-role-source><cmr-field>

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

</ejb-relationship-role>

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

Java certification success, Part 3: SCBCD Page 51 of 115

Page 52: Java Certification Success, Part 3: SCBCD

<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 eitherthe local interface of the entity bean or a collection (eitherjava.util.Collection or java.util.Set) of the same, so these are thevalid types of CMR fields of an entity bean. The set() method for therelationship must take as an argument the entity bean's local interface or acollection of the same.

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

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

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

Page 52 of 115 Java certification success, Part 3: SCBCD

Page 53: Java Certification Success, Part 3: SCBCD

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 is linked 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 thatone instance of Bean1 has a reference to one instance of Bean2, but theinstance of Bean2 has no reference to the instance of Bean1. As the questionstates, ba1 is linked to bb1 and ba2 is linked to bb2.

The statement ba1.setBean2(ba2.getBean2()) retrieves the Bean2object that ba2 is referencing and assigns it to ba1. Because it is a one-to-onerelationship, only one bean can have a reference to another, which means thatafter the execution of the above statement ba2 is not referencing anything.Thus, ba2.getBean2() returns null. Therefore, choice A is incorrect.

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

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

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

Java certification success, Part 3: SCBCD Page 53 of 115

Page 54: Java Certification Success, Part 3: SCBCD

Choice F is incorrect because an instance of Bean1 does not have a referenceto another instance of Bean1.

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

Summary

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

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

Page 54 of 115 Java certification success, Part 3: SCBCD

Page 55: Java Certification Success, Part 3: SCBCD

Section 8. CMP entity bean lifecycle

Overview

CMP entity beans support instance pooling, just like stateless session beans.They are also passivated and activated, but unlike the stateful session beans,the bean state is not serialized.

The container interacts with the database when a new entity is to be created ordeleted. Similarly, it manages the transactions and the synchronization of thebean state with the database. Let's examine the important events in the life ofan entity bean instance and how the container interacts with the bean duringthese events.

State diagram

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

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

Java certification success, Part 3: SCBCD Page 55 of 115

Page 56: Java Certification Success, Part 3: SCBCD

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 anEntityContext object is passed by invoking the setEntityContext()method. Now the bean instance is in the Pooled state. In this state, the beaninstance can service finder methods, select methods, and home businessmethods, because they do not require the bean to have an identity. The beaninstance can service entity-specific client calls when it is in the Ready state.

Two possible transitions from the Pooled to the ready state exist: through theejbCreate<METHOD>(...) and ejbPostCreate<METHOD>(...) methods,or through the ejbActivate() method. The container might decide to removea bean from 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 beaninstance.

Client invokes a create() method on the bean home° A bean instance is chosen from the pool and its corresponding

ejbCreate<METHOD>() method is invoked.° A primary key is created and a new record is inserted.° The bean instance is associated with the EJB object.° The corresponding ejbPostCreate<METHOD>() method of the bean is

invoked.° An EJB Object reference is returned to the client.° Now the bean instance is in the Ready state.

Client invokes a finder method on the bean home° A bean instance is chosen from the pool and its corresponding ejbFind()

method is called.° The ejbFind() method verifies if the entity exists in the database.° If the entity exists, the bean instance returns the primary key to the bean

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

Page 56 of 115 Java certification success, Part 3: SCBCD

Page 57: Java Certification Success, Part 3: SCBCD

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

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

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

Client invokes the remove() method on the bean's EJB Object or EJBhome° 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 andcontainer in defining them.

setEntityContext()

The entity object identity is not available in the setEntityContext() method.The programmer can use this method to allocate any resources that are to beheld by the instance for its lifetime.

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

Java certification success, Part 3: SCBCD Page 57 of 115

Page 58: Java Certification Success, Part 3: SCBCD

The container passes a reference to the EntityContext interface to the entitybean instance as an argument to this method. The container invokes thismethod after it creates an instance and before it puts the instance into the poolof available instances. This method is executed within an unspecifiedtransaction context.

unsetEntityContext()

The container invokes this method when the container wants to reduce thenumber of instances in the pool. After this method completes, the containermust not reuse this instance. The programmer can use this method to free anyresources that are held by the instance.

The bean identity is not available during this method also.

ejbCreate<METHOD>()

The container invokes the ejbCreate<METHOD>() methods when a clientinvokes a matching create<METHOD>() method on the entity bean's homeinterface. The Bean Provider can use this method to initialize the instance inthis method from the input arguments. He must not attempt to modify the valuesof CMR fields in this method because the primary key is not yet available. Thismethod should return null. The ejbCreate<METHOD>>() methods and thesubsequent database insertion operations execute in the same transactioncontext as the create<METHOD>() methods previously invoked.

ejbPostCreate<METHOD>()

The ejbPostCreate<METHOD>() methods have the same set of argumentsas the corresponding ejbCreate<METHOD>() methods, but their return type isvoid.

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 thebean. This method executes in the same transaction context as thecorresponding ejbCreate<METHOD>() method. The container creates theprimary key of the entity before it invokes the ejbPostCreate<METHOD>()method.

ejbActivate()

The ejbActivate() method is invoked on an entity bean instance afteractivation. The primary key of the associated entity object is available to theinstance during this method. The bean can use this method to acquireadditional resources that it needs while it is in the Ready state. The containerinvokes this method within an unspecified transaction context.

ejbPassivate()

The ejbPassivate() method is invoked when the container decides to

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

Page 58 of 115 Java certification success, Part 3: SCBCD

Page 59: Java Certification Success, Part 3: SCBCD

disassociate the instance from an entity object identity. The primary key of theassociated entity object is available to the instance during this method. Thebean can use this method to release the resources that it acquired during theejbActivate() method. The container invokes this method within anunspecified transaction context.

ejbRemove()

The ejbRemove() method is invoked in response to a client-invoked removeoperation 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 therelationships in which it participates and then removes its persistent data. TheejbRemove() method and the database delete operations are performed inthe transaction context of the invoked remove() method. The bean instance isin the Ready state when ejbRemove() is invoked and it will be entered into thepool when the method completes.

ejbLoad()

The ejbLoad() method is called when the container needs to synchronize thestate of an enterprise bean instance with the entity object's persistent state.This method can be used to recompute or initialize the values of any instancevariables that depend 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 synchronizethe state of the entity object in the database with the state of the enterprisebean instance. This method is invoked in the same transaction context as theprevious ejbLoad() or ejbCreate() method invoked on the instance.

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

ejbFind<METHOD>()

The ejbFind<METHOD>() methods are generated at the entity beandeployment time using the container provider's tools. The container invokes theejbFind<METHOD>() method on an instance when a client invokes amatching find<METHOD>() method on the bean home. The method is invoked

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

Java certification success, Part 3: SCBCD Page 59 of 115

Page 60: Java Certification Success, Part 3: SCBCD

on a pooled entity instance, which remains pooled even after the method call.This method is invoked in the transaction context of the matchingfind<METHOD>() method.

ejbSelect<METHOD>()

The ejbSelect<METHOD>() methods are not directly exposed to the client inthe home or component interface because they are for the internal use of thebean. They are declared as abstract by the bean provider and theirimplementation is generated at deployment time using the container provider'stools. These methods are typically called within a home or business method.They execute in the transaction context determined by the transaction attributeof the invoking method.

ejbHome<METHOD>()

The ejbHome<METHOD>() methods are invoked when the container selectsthe instance to execute a matching client-invoked home business method. Thepooled instance, which is chosen for the method execution, remains in thepooled state after the execution of the home method. It is invoked in the sametransaction context as the triggering home method. The entity Bean Providerprovides the implementation of the ejbHome<METHOD>(...) method. as anEJB-QL expression in the deployment descriptor. Because the bean identity isnot available within this method, the bean must not attempt to access itspersistent state or relationships using the accessor methods.

Sample questions

Question 1:

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

Choices:

° A. ejbCreate<METHOD>()° B. ejbSelect<METHOD>()° C. ejbLoad<METHOD>()° D. ejbRemove<METHOD>()° E. ejbFind<METHOD>()

Correct choice:

A and E

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

Page 60 of 115 Java certification success, Part 3: SCBCD

Page 61: Java Certification Success, Part 3: SCBCD

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.

Choice B is incorrect because the ejbSelect<METHOD>() methods areinternal to the bean class and have no matching method in the home interface.They are usually invoked by an ejbHome<METHOD>() method or anothermethod internal to the 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 entitybean class.

Please refer to sections 10.5.2 and 10.5.3 of the EJB 2.0 specification forfurther details (see Resources on page113 ).

Question 2:

It is mandatory that certain resources held by an entity bean be released whenthe bean leaves the instance pool to be garbage collected. Which of thefollowing methods should contain the code for doing this?

Choices:

° A. ejbRemove()° B. ejbPassivate()° C. unsetEntityContext()° D. finalize()

Correct choice:

C

Explanation:

The ejbRemove() method is invoked when the client application invokes theremove() method on the bean's EJBObject or EJBHome. It notifies the entitybean instance that its data is about to be removed from the database. The beanthen transitions into the Pooled state. So choice A is incorrect.

The ejbPassivate() method is invoked when a bean instance isdisassociated from its EJBObject and is moved to the Pooled state. Themethod that is called when the bean instance moves from the instance pool to

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

Java certification success, Part 3: SCBCD Page 61 of 115

Page 62: Java Certification Success, Part 3: SCBCD

be garbage collected is unsetEntityContext(). After this method is called,the bean instance is eligible for garbage collection. Therefore, choice C iscorrect.

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

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

Summary

This section traced the lifecycle of a CMP entity bean. We have seen thatcreation, passivation, activation, and removal of entity beans are significantlydifferent from that of session beans. You should be aware of the exactsequence of events for each state transition of the bean instance.

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

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

Page 62 of 115 Java certification success, Part 3: SCBCD

Page 63: Java Certification Success, Part 3: SCBCD

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, thecontainer invokes the setEntityContext() method on the instance, passinga reference to its EntityContext. As the bean instance is switched betweenEJB Objects by the container, the information obtained from EntityContext(such as the primary key) is subject to change.

The EntityContext interface extends javax.ejb.EJBContext, which isalso extended 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:

° EJBLocalObject getEJBLocalObject(), which returns a reference tothe 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(), which returnsan instance of a java.security.Principal that identifies the invoker of

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

Java certification success, Part 3: SCBCD Page 63 of 115

Page 64: Java Certification Success, Part 3: SCBCD

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 test ifthe current transaction has been marked for rollback.

° javax.transaction.UserTransaction getUserTransaction(),which returns an instance of a javax.transaction.UserTransactioninterface. Entity bean instances must not call this method because they donot support BMT demarcation.

Operations allowed in EntityBean methods

Let's look at which operations are allowed to be performed in the methodsdefined in an entity bean. If an entity bean instance attempts to invoke a methodof the EntityContext interface, and access is not allowed, the containerthrows a java.lang.IllegalStateException exception.

You are not allowed to invoke the getEJBObject(),getEJBLocalObject(), and getPrimaryKey() methods in the methods inwhich there is no entity object identity associated with the instance, whichinclude setEntityContext(), unsetEntityContext(),ejbCreate<METHOD>(), and ejbHome<METHOD>(). When a new entity iscreated, the bean identity and primary key are not available until theejbPostCreate<METHOD>() method is invoked.

The getCallerPrincipal() and isCallerInRole() methods ofEntityContext are not allowed to be invoked in methods in which thecontainer does not have a client security context, which include thesetEntityContext(), unsetEntityContext(), ejbPassivate(), andejbActivate() methods.

The getRollbackOnly() and setRollbackOnly() methods, which allowgetting and setting of the transaction status, are not allowed in methods forwhich the container does not have a meaningful transaction context, whichinclude the setEntityContext(), unsetEntityContext(),ejbPassivate(), and ejbActivate() methods.

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

Page 64 of 115 Java certification success, Part 3: SCBCD

Page 65: Java Certification Success, Part 3: SCBCD

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

The getEJBHome() and getEJBLocalHome() methods can be invoked in allthe bean methods except the constructor.

Primary keys

A primary key is an object that uniquely identifies an entity bean within its EJBhome. If two entity EJB Objects from the same home have the same primarykey, they are considered identical.

A primary key can be of two types: Single field keys or composite keys. A singlefield primary key maps to a single persistence field in the entity bean. Acomposite primary key maps to more than one persistence field in the entitybean.

A primary key class has the following requirements:

° Must be a legal Value Type in RMI-IIOP° Must provide suitable implementation of the hashCode() and equals()

methods° Must be serializable and public

Single field primary keys

We can use a single CMP field of the primary key by declaring the field nameand the class name in the deployment descriptor. Typically, String and wrapperclasses are 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 asthe primary key type. The <prim-key-class> element contains the fullyqualified name 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);...

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

Java certification success, Part 3: SCBCD Page 65 of 115

Page 66: Java Certification Success, Part 3: SCBCD

}

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

A composite primary key is made up of the CMP fields of the bean. The classmust be public and must have a public constructor with no parameters. Allfields in the primary key class must be declared as public, and their namesmust correspond to the entity bean field names that comprise the key. The<primkey-field> element is not used for composite keys.

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

}public boolean equals(Object obj) {

if (obj==null || ! (obj instanceof StudKey))return false;

StudKey key = (StudKey) obj;return studentId.equals(key.studentId)

&courseId.equals(key.courseId);}public int hashCode() {

return studentId.hashCode() ^ courseId.hashCode();}}

Undefined primary keys

The bean developer can defer declaring the primary key to the deployer, whichallows the deployer to choose a database-specific key at deployment time. TheBean Provider must specify the primary key class in the deployment descriptoras type java.lang.Object. The container generates the primary key valuewhen the entity bean instance is created.

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

Page 66 of 115 Java certification success, Part 3: SCBCD

Page 67: Java Certification Success, Part 3: SCBCD

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()methods can be successfully invoked (that is, without throwing an exception) onthe entity context object.

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

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

Question 2:

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

Choices:

° A. The primary key class must be private and be an inner class of the

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

Java certification success, Part 3: SCBCD Page 67 of 115

Page 68: Java Certification Success, Part 3: SCBCD

entity bean class.

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

° C. All fields of the primary key class must follow the JavaBeans conventions-- that is, the fields must be private, and public accessor or mutator methodsmust 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 key class.

° F. ba1.getBean1() == null

Correct choice:

D and E

Explanation:

Choice A is incorrect because the primary key class must be declared publicand not private.

Choice B is incorrect because the primary key class does not need to bedeclared abstract. The container should be allowed to use the primary classwithout having to extend it.

Choice C is incorrect because there is no such requirement. All fields of theprimary key class must be declared public, even if this means that theencapsulation of the class 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 on page113 ).

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

Page 68 of 115 Java certification success, Part 3: SCBCD

Page 69: Java Certification Success, Part 3: SCBCD

Summary

This section covered the methods defined in the EntityContext interface,which is the interface the entity bean instance uses to interact with thecontainer. Some operations may require a valid transaction context or securitycontext to be available when they are invoked, while some others might workonly for CMTs. Hence, it is important to understand which operations areallowed to be performed within each callback method of the bean and why.

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

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

Java certification success, Part 3: SCBCD Page 69 of 115

Page 70: Java Certification Success, Part 3: SCBCD

Section 10. EJB-QL

Purpose of EJB-QL

EJB-QL is a query specification language for the finder and select methods ofCMP entity beans. This language is portable across databases and dataschemas. It is possible to parse and validate EJB-QL queries before entitybeans are deployed because the language is defined in terms of the abstractpersistent schema of the entity beans. These queries are written by the entityBean Provider in the deployment descriptor. Container tools then translatethese queries into the target language of the underlying data store.

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

° As queries for selecting entity objects through finder methods defined in thehome interface

° As queries for selecting entity objects or other values derived from an entitybean's abstract schema type through select methods defined on the entitybean class

Using EJB-QL

Basic syntax

An EJB-QL query is a string that consists of the following three clauses:

° A SELECT clause, which determines the type of the objects or values to beselected

° A FROM clause, which provides declarations that designate the query domain° An optional WHERE clause, which may be used to restrict the results returned

by the query

All standalone identification variables in the SELECT clause must be qualified bythe OBJECT 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

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

Page 70 of 115 Java certification success, Part 3: SCBCD

Page 71: Java Certification Success, Part 3: SCBCD

single-valued field. In the example below, name is a CMP field, and address isa CMR field that contains 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 ofall the customers:

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

Note that path expressions cannot navigate beyond CMP fields. The followingquery is 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 followingquery is invalid:

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 expressions

We can use conditional expressions in the WHERE clause to restrict the resultsof the query.

The following query returns only the customers based in California:

SELECT OBJECT(c) FROM Customer c WHERE c.address.state = "CA"

Likewise, the following query returns only the customers who have placedorders:

SELECT OBJECT(c) FROM Customer WHERE c.orders IS NOT EMPTY

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

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

Java certification success, Part 3: SCBCD Page 71 of 115

Page 72: Java Certification Success, Part 3: SCBCD

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

Here the age and name of the customer are passed as parameters to the query.The DISTINCT keyword is used to specify that duplicate values must beeliminated from the query results.

BETWEEN expressions

The BETWEEN clause is used to specify a range of values. It may be used onlyon numeric primitives and their wrappers. It is inclusive of the upper and lowerlimits.

The following query returns all the customers between the ages of 20 and 30:

SELECT OBJECT(c) FROM Customer c WHERE c.age BETWEEN 20 AND 30

IN expressions

The IN operator in the WHERE clause tests for membership in a list of literalstring values:

SELECT OBJECT(c) FROM Customer WHERE c.address.state IN ("TX","CA")SELECT OBJECT(c) FROM Customer WHERE c.address.state NOT IN ("TX","CA")

Here, the first query returns the customers from the given states and the secondreturns those who are not from these states.

LIKE expressions

The LIKE operator allows you to select CMP String fields that match a givenpattern. The "%" symbol stands for any sequence of characters, while the "_"symbol stands for a single character.

SELECT OBJECT(c) FROM Customer c WHERE address.phone LIKE "45%3"

The query returns customers whose phone numbers are "453" and "45993," butnot "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"

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

Page 72 of 115 Java certification success, Part 3: SCBCD

Page 73: Java Certification Success, Part 3: SCBCD

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

The query element has two sub-elements: <query-method> and <ejb-ql>.The <query-method> element identifies the finder method, and the<ejb-ql> element declares the EJB-QL statement.

Every entity bean referenced in an EJB-QL statement must have an identifierknown as "abstract schema name," which is declared by the<abstract-schema-name> element.

Consider the following home interface definition:

public interface CustomerHomeLocal extends EJBLocalHome{public CustomerLocal findByPrimaryKey(Integer primaryKey)throws

FinderException;public Collection findByCity(String city) throws FinderException;

}

EJB-QL declarations are not allowed for findByPrimaryKey() methods.However, the findByCity() method needs to be mapped to a query elementas shown below:

<entity><ejb-name>CustomerEJB</ejb-name>

...<abstract-schema-name>Customer</abstract-schema-name>

<cmp-field><field-name>city</field-name></cmp-field>...<query>

<query-method><method-name>findByCity</method-name><method-params>

<method-param>java.lang.String</method-param></method-params>

</query-method><ejb-ql>

SELECT OBJECT(c) FROM Customer c where c.city = ?1</ejb-ql>

</query></entity>

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

Java certification success, Part 3: SCBCD Page 73 of 115

Page 74: Java Certification Success, Part 3: SCBCD

Using EJB-QL with select methods

A select method is a special type of query method, not directly exposed throughthe client 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 methodscan declare zero or more arguments. An ejbSelect() method definition isshown in the following example:

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

}

The select methods are not declared in the home interfaces, so theejbSelect() 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 entitybean instance on which it is invoked, so it can be used to query across all theentity beans declared in the same deployment descriptor.

Sample questions

Question 1:

Select all the expressions that are semantically equivalent to the BETWEEN

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

Page 74 of 115 Java certification success, Part 3: SCBCD

Page 75: Java Certification Success, Part 3: SCBCD

expression given below:

person.age BETWEEN 20 and 25

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

Choices:

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

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

° 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(see Resources on page113 ).

Question 2:

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

Choices:

° A. EJB-QL queries are portable across databases, data schemas, and EJBcontainers.

° B. EJB-QL queries can be used to insert records into the database.° C. The SELECT clause must not use the OBJECT operator to qualify path

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

Correct choice:

A and C

Explanation:

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

Java certification success, Part 3: SCBCD Page 75 of 115

Page 76: Java Certification Success, Part 3: SCBCD

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 dataaccess code, so they are independent of the underlying data store structure andschema. Thus, choice A is correct.

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 bythe OBJECT operator. However, the SELECT clause must not use the OBJECToperator to qualify path expressions. So choice C is correct.

EJB-QL allows SELECT clauses to return any CMP or single CMR field.However, the path expressions in these clauses must not end with acollection-based relationship field. So choice D is incorrect.

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

Summary

This section demonstrated how to use EJB-QL queries to access the datarequired by the finder and select methods of an entity bean. We discussed thecorrect and incorrect syntaxes for an EJB-QL query and how to define suchqueries in the deployment descriptor. We reviewed how the results of the querycan be restricted using conditional expressions, BETWEEN expressions, LIKEexpressions, and comparison expressions.

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

Page 76 of 115 Java certification success, Part 3: SCBCD

Page 77: Java Certification Success, Part 3: SCBCD

Section 11. MDB component contract

Message-driven beans

Message-driven beans (MDBs) are asynchronous JMS message consumers.They do not have home or component interfaces because clients never callthem 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 forthe bean instance to receive the message or process it. After sending themessage, the client can continue doing its job. However, there is no guaranteethat the bean will receive the messages in the same order in which they havebeen sent.

MDB lifecycle

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

The life of an MDB instance starts when the container invokesnewInstance() on the MDB class to create a new instance. Next, thecontainer calls setMessageDrivenContext() followed by ejbCreate() onthe instance. The bean then enters the Ready state and is ready to consumemessages.

When a message arrives for the bean, the container invokes the onMessage()method of one of the available instances, passing a Message object inargument. Messages can be consumed and processed concurrently by using

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

Java certification success, Part 3: SCBCD Page 77 of 115

Page 78: Java Certification Success, Part 3: SCBCD

multiple instances of the same type.

The container invokes ejbRemove() on the bean instance when it no longerneeds the 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.

MessageDrivenBean

The MessageDrivenBean interface defines lifecycle event notificationmethods invoked by the container on the bean instance.

The methods defined by this interface are as follows:

° void setMessageDrivenContext(MessageDrivenContext ctx)

° void ejbRemove()

The setMessageDrivenContext() method, which is invoked at thebeginning of the bean lifecycle, provides the MDB instance with a reference toits MessageDrivenContext.

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

MessageListener

A 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 forthe bean to service. It contains the business logic that handles the processing ofthe message.

MessageDrivenContext

The MessageDrivenContext interface gives the MDB instance access to theinstance's runtime context maintained by the container. The context objectremains associated with the instance for the lifetime of the instance. Thisinterface contains only methods inherited from EJBContext.

The methods of MessageDrivenContext that are allowed to be called by

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

Page 78 of 115 Java certification success, Part 3: SCBCD

Page 79: Java Certification Success, Part 3: SCBCD

MDBs are as follows:

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

° public void setRollbackOnly(), which marks the current transactionfor rollback

° public UserTransaction getUserTransaction(), which returns theUserTransaction reference

The getRollbackOnly() and setRollbackOnly() methods must beinvoked only in the onMessage() method. They are onlyfor MDBs using CMTdemarcation.

The getUserTransaction() method can be invoked in the ejbCreate(),ejbRemove(), and onMessage() methods. The getUserTransaction()method is only for beans using BMT demarcation.

Configuring the MDB

We need to configure some elements in the deployment descriptor to enablethe MDB 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 whetherto associate 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 topicsubscription is intended to be durable or non-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>

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

Java certification success, Part 3: SCBCD Page 79 of 115

Page 80: Java Certification Success, Part 3: SCBCD

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

The JMS message service expects the container to acknowledge if a messagehas been successfully delivered to the MDB. If an acknowledgement is notreceived, the JMS service resends the same message. If the bean uses CMTtransaction demarcation, the message acknowledgment is handledautomatically as a part of the transaction commit. For beans using BMTtransaction demarcation, the Bean Provider can indicate in the<acknowledge-mode> element whether JMS AUTO_ACKNOWLEDGE orDUPS_OK_ACKNOWLEDGE should be used. Using AUTO_ACKNOWLEDGEautomatically acknowledges the successful delivery of a message. UsingDUPS_OK_ACKNOWLEDGE instructs the container to lazily acknowledge thedelivery of messages, which makes the server more efficient at the risk ofduplicate messages.

Responsibilities of the Bean Provider

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

Requirements of the MDB class° The class must implement MessageDrivenBean and MessageListener

interfaces.° The class must be declared public but neither final nor abstract.° The class must have a public constructor that takes no arguments.° The class must not declare the finalize() method.° The class must implement the ejbCreate() method.

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

Requirements of the onMessage() method° The method must be public and must take a single argument of type

javax.jms.Message.° The return type must be void.° The method must neither be declared final nor static.

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

Page 80 of 115 Java certification success, Part 3: SCBCD

Page 81: Java Certification Success, Part 3: SCBCD

° The throws clause must not contain any application exception types.

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

Responsibilities of the container provider

The container provider is responsible for providing the deployment tools and formanaging the MDB instances at runtime. The container must ensure that thebean instances are always thread-safe.

The container may generate additional classes when the MDB is deployed.

It must support the deployment of an MDB as the consumer of a JMS queue ora durable 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:

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

Java certification success, Part 3: SCBCD Page 81 of 115

Page 82: Java Certification Success, Part 3: SCBCD

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 ahome interface. MDBs are anonymous, that is they don't have a visible clientidentity. So the getCallerPrincipal() and isCallerInRole() methods,which need the security context of the caller, cannot be invoked. However,MDBs are transactional, so the getRollbackOnly() method can be invoked.

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

Question 2:

Which are the interfaces that must be implemented by an MDB?

Choices:

° A. MessageDrivenObject° B. MessageDrivenBean° C. MessageListener° D. MessageDrivenContext° E. MSListener

Correct choice:

B and C

Explanation:

The MessageDrivenBean and MessageListener interfaces should beimplemented by any MDB class. The onMessage() method is defined in theMessageListener interface. This method passes the messages to the MDBby the container. The MessageDrivenBean interface defines two callbackmethods -- setMessageDrivenContext() and ejbRemove(). ThesetMessageDrivenContext() method is called at the beginning of theMDB's lifecycle and provides the bean with a reference to itsMessageDrivenContext interface.

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

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

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

Page 82 of 115 Java certification success, Part 3: SCBCD

Page 83: Java Certification Success, Part 3: SCBCD

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

Summary

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

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

Java certification success, Part 3: SCBCD Page 83 of 115

Page 84: Java Certification Success, Part 3: SCBCD

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 notnested ones. In nested transactions, a new transaction can be started, while atransaction is currently active.

In EJB development, the Bean Provider can choose between usingprogrammatic transaction demarcation in the enterprise bean code (BMTdemarcation) or declarative transaction demarcation performed automatically bythe EJB container (CMT demarcation).

A session bean or an MDB can use BMT or CMT, but not both at the sametime. An entity bean can use only CMT.

Container-managed transactions

The EJB container is responsible for managing transaction boundaries in thecase of a CMT bean. When a client calls a method on an enterprise bean, thenew method can run in the caller's transaction, start a new transaction, or runwithout a transaction. The action taken by the EJB container in this case isdecided by the transaction attribute defined for the method.

Transaction attribute basics

Transaction attributes must be given for business methods in the case of bothentity and session beans. They must not be specified for the methods of asession bean's home interface because these methods are not considered aspart of a client's transaction. This rule, however, is not the case for entity beans,in which home interface methods like create() and remove() involvedatabase operations and are hence transactional. For an MDB, the transactionattribute can only be specified for the bean's onMessage() method, becausethere is no client view.

The six possible transaction attributes are Required, RequiresNew,NotSupported, Supports, Mandatory, and Never. Let's look at how eachof these 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.

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

Page 84 of 115 Java certification success, Part 3: SCBCD

Page 85: Java Certification Success, Part 3: SCBCD

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 method runswithin an unspecified transaction context.

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

° Never: If a remote client invokes a bean method with a meaningfultransaction context, the container throws a java.rmi.RemoteException.If a local client invokes a bean method with a meaningful transaction context,the container throws a javax.ejb.EJBException. Otherwise, the beanmethod runs within an unspecified transaction context.

Restrictions on transaction attributes

For MDBs, only the Required and NotSupported transaction attributes maybe used because they have no calling clients and hence the other attributes donot apply.

If an enterprise bean implements the SessionSynchronization interface,only the transaction attributes Required, RequiresNew, or Mandatory areallowed, to ensure that the method is participating in a transaction. For portableentity beans that use EJB 2.0 CMP also, only the Required, RequiresNew, orMandatory transaction 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 ifa transaction has been marked for rollback. For these operations to work, themethod in which they are invoked should be in a transaction, so its attributemust be Required, RequiresNew, or Mandatory.

Roles and responsibilities

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

Java certification success, Part 3: SCBCD Page 85 of 115

Page 86: Java Certification Success, Part 3: SCBCD

The Bean Provider must use the <transaction-type> element to declarewhether the bean uses CMT or BMT demarcation. The Application Assembleruses the <container-transaction> element to define the transactionattributes. The Deployer is responsible for ensuring that the methods of theenterprise beans deployed with CMT demarcation have been assigned atransaction attribute.

In the following example, all the methods of CustomerEJB have been given thetransaction attribute Required, except the addBonus() method, which hasbeen given the attribute Mandatory:

<enterprise-beans><session>

<ejb-name>CustomerEJB</ejb-name>...<transaction-type>Container</transaction-type>

</session></enterprise-beans><assembly-descriptor>

<container-transaction><method>

<ejb-name>CustomerEJB</ejb-name><method-name>*</method-name>

</method><trans-attribute>Required</trans-attribute>

</container-transaction><container-transaction>

<method><ejb-name>CustomerEJB</ejb-name><method-name>addBonus</method-name>

</method><trans-attribute>Mandatory</trans-attribute>

</container-transaction></assembly-descriptor>

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

If the methods are overloaded, the optional <method-params> and<method-param> elements allow you to identify the appropriate method.

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

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

Page 86 of 115 Java certification success, Part 3: SCBCD

Page 87: Java Certification Success, Part 3: SCBCD

Bean-managed transactions

In the case of BMTs, the bean itself manages transactions programmatically inthe business methods. The Bean Provider uses thejavax.transaction.UserTransaction interface to explicitly demarcatetransactions. A bean instance that starts a transaction must complete thetransaction before it starts a new one.

In the following example, we first get a reference to the UserTransactionobject, then start a new transaction by invoking the begin() method on it. Wethen add the transactional code, and finally we invoke the commit() method toend the transaction. To roll back the current transaction, we can invoke therollback() 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

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 incomingtransaction is suspended.

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

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

Java certification success, Part 3: SCBCD Page 87 of 115

Page 88: Java Certification Success, Part 3: SCBCD

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

Methods of UserTransaction

The UserTransaction interface defines the following methods that areinvoked by the 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 the currentthread.

° void setRollbackOnly(): Modifies the transaction associated with thecurrent thread such that the only possible outcome of the transaction is toroll 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 the timeoutvalue that is associated with the transactions started by the current threadwith the begin method.

Sample questions

Question 1:

Which of the following statements about transactions in EJB 2.0 are true?

Choices:

° A. The create() and remove() methods in session beans do not have

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

Page 88 of 115 Java certification success, Part 3: SCBCD

Page 89: Java Certification Success, Part 3: SCBCD

transaction attributes.° B. Nested transactions are supported for BMT enterprise beans.° C. Isolation levels can be specified for CMT session beans.° D. A BMT MDB must begin and end a transaction within the onMessage()

method.° E. If the transaction attribute of a bean method is Mandatory and a remote

client invokes it without a transaction, aTransactionMandatoryException is thrown.

Correct choice:

A and D

Explanation:

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

Nested transactions and isolation levels are not supported in EJB 2.0, sochoices B and C are incorrect.

A BMT MDB must begin and end a transaction within the onMessage()method -- that is, a transaction cannot span multiple method calls. So choice Dis correct.

If the transaction attribute of a bean method is Mandatory and a remote clientinvokes it without a transaction, a TransactionRequiredException isthrown (there is no such exception as TransactionMandatoryException).So choice E is incorrect.

Question 2:

Which of the following transaction attributes may cause the container to throwan exception whenever the transaction context does not satisfy theirrequirements?

Choices:

° A. Required° B. RequiresNew° C. Never° D. Mandatory° E. Supports° f. NotSupported

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

Java certification success, Part 3: SCBCD Page 89 of 115

Page 90: Java Certification Success, Part 3: SCBCD

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 clientmakes a call in an unspecified transaction context, the EJB container is requiredto throw the javax.transaction.TransactionRequiredExceptionexception if the client is a remote client or thejavax.ejb.TransactionRequiredLocalException if the client is a localclient.

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 throwthe java.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 anexception, so the remaining options are incorrect. Therefore, C and D arecorrect, 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 on page113 ).

Summary

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

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

Page 90 of 115 Java certification success, Part 3: SCBCD

Page 91: Java Certification Success, Part 3: SCBCD

Section 13. Exceptions

Application exceptions

An application exception is an exception defined in the throws clause of amethod in the bean's home or component interface. An application exceptionclass must be a direct or indirect subclass of java.lang.Exception, butneither of java.lang.RuntimeException norjava.rmi.RemoteException.

These exceptions typically indicate application-level problems such as illegalvalues of the input arguments to a business method. They should be reported tothe client without any modification. An application exception does not cause anautomatic rollback of an ongoing transaction, and the client can continue towork with the bean instance.

System exceptions

A system exception is an exception that the client does not expect or is notexpected to recover from. All unchecked exceptions as well asjava.rmi.RemoteException belong to this category. System-level errorsmay be encountered during the execution of a session or an entity beanbusiness method, an MDB onMessage() method, or a container callbackmethod. Some examples include:

° Failure to obtain a database connection° JNDI exceptions° Unexpected RemoteException from invocation of other enterprise beans° Unexpected RuntimeException

° JVM errors

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

Responsibilities of the container provider

The Bean Provider expects the container to perform certain tasks when

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

Java certification success, Part 3: SCBCD Page 91 of 115

Page 92: Java Certification Success, Part 3: SCBCD

exceptions are thrown. Let's examine these in detail for different situations.

Application exceptions

If the bean method is running in the context of the caller's transaction, thecontainer re-throws the exception to the client. The client can continue workingwith the transaction but cannot commit the transaction if the bean instance hasinvoked the setRollbackOnly() method. This situation does not arise in thecase of beans using BMT demarcation because transactions cannot propagateinto 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 thecontainer rolls back the transaction and re-throws the exception. For beansexecuting within an unspecified transaction context, the exception is simplyre-thrown.

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

System exceptions

For all bean types, system exceptions are logged, the existing transaction ismarked for rollback, and the bean instance is discarded.

If the bean was executing within a client-initiated transaction, the containerthrows TransactionRolledbackException to remote clients andTransactionRolledbackLocalException to local clients. This situationdoes not arise in the case of beans using BMT demarcation, becausetransactions cannot propagate 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 theydo not have any client view.

Responsibilities of the Bean Provider

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

Application exceptions

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

Page 92 of 115 Java certification success, Part 3: SCBCD

Page 93: Java Certification Success, Part 3: SCBCD

° 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 throws clauseof 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 such thata client's attempt to continue and/or commit the transaction does not result inthe loss of data integrity.

System exceptions° If the bean method encounters a RuntimeException or error, it should

simply propagate the error to the container.

° If the bean method performs an operation that results in a checkedexception that the client is not expecting, the bean method should wrap theoriginal exception within a javax.ejb.EJBException and throw the latterto the container.

° javax.ejb.EJBException is a subclass of thejava.lang.RuntimeException, and therefore does not have to be listedin the throws clauses of the business methods.

Common exceptions in EJB

Let's now explore some of the most common exceptions encountered in EJBprogramming.

Standard application exceptions are:

° CreateException

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

Java certification success, Part 3: SCBCD Page 93 of 115

Page 94: Java Certification Success, Part 3: SCBCD

° DuplicateKeyException

° RemoveException

° FinderException

° ObjectNotFoundException

CreateException

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

DuplicateKeyException

The javax.ejb.DuplicateKeyException exception is thrown if an entityobject cannot be created because an entity with the same key already exists.This exception is thrown by the create methods defined in an entity bean'shome interface. It is a subclass of javax.ejb.CreateException.

RemoveException

The javax.ejb.RemoveException exception may be thrown whenattempting to remove a bean when the enterprise bean or the container doesnot allow it to be removed.

FinderException

The finder methods of an entity bean throw this exception to report a failurewhen finding the requested entity (or entities). It must be included in the throwsclause of every finder method of the entity bean's home interface.

ObjectNotFoundException

The javax.ejb.ObjectNotFoundException exception is thrown by asingle-entity finder method to indicate that the specified entity does not exist. Itis a subclass of javax.ejb.FinderException.

Some of the most common system exceptions are:

° EJBException

° IllegalStateException

° NoSuchEntityException

° TransactionRequired(Local)Exception

° TransactionRolledback(Local)Exception

EJBException

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

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

Page 94 of 115 Java certification success, Part 3: SCBCD

Page 95: Java Certification Success, Part 3: SCBCD

container to report that the invoked business or callback method could notcomplete successfully because of some unexpected error. The container maythrow it to local clients when it catches a system exception. It is a subclass ofjava.lang.RuntimeException.

IllegalStateException

This exception is also a subclass of java.lang.RuntimeException. Thecontainer throws this exception to the enterprise bean to signal that a methodhas been invoked at an illegal or inappropriate time, like callingsetRollbackOnly() within a method executing in an unspecified transactioncontext.

NoSuchEntityException

The javax.ejb.NoSuchEntityException exception is thrown by an entitybean instance to report that the referenced entity was removed from thedatabase. This exception may be thrown by ejbLoad(), ejbStore() and anybusiness methods. It is a subclass of javax.ejb.EJBException.

TransactionRequiredException/TransactionRequiredLocalException

If a bean method marked with the Mandatory transaction attribute is invokedby a non-transactional client method,javax.transaction.TransactionRequiredException is thrown if theclient is remote and javax.ejb.TransactionRequiredLocalExceptionis thrown if the client is local. TransactionRolledbackException is asubclass of java.rmi.RemoteException andTransactionRolledbackLocalException is a subclass ofjavax.ejb.EJBException.

TransactionRolledbackException/TransactionRolledbackLocalException

If a client receivesjavax.transaction.TransactionRolledbackException orjavax.ejb.TransactionRolledbackLocalException, the client knowsfor certain that the transaction has been marked for rollback.TransactionRolledbackException is a subclass ofjava.rmi.RemoteException, whileTransactionRolledbackLocalException is a subclass ofjavax.ejb.EJBException.

Sample questions

Question 1:

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

Java certification success, Part 3: SCBCD Page 95 of 115

Page 96: Java Certification Success, Part 3: SCBCD

Which exception would a client receive if a javax.ejb.EJBException isthrown from a business method whose transaction attribute is Mandatory?

Choices:

° A. javax.ejb.EJBException° B. javax.ejb.TransactionRolledbackLocalException° C. javax.transaction.TransactionRequiredException° D. java.rmi.RemoteException° E. javax.transaction.TransactionRolledbackException° F. javax.ejb.TransactionRequiredLocalException

Correct choice:

B

Explanation:

The critical point here is to understand the information contained in the questionstatement. First, we know that the bean throws a javax.ejb.EJBException,so we know we are dealing with a local client. Therefore, we can eliminatechoices C, D, and E right away.

Second, because the transaction attribute of the business method isMandatory, we know for sure that a client transaction existed (otherwise thecontainer would have thrownjavax.ejb.TransactionRequiredLocalException), so choice F isincorrect.

Because the javax.ejb.EJBException is not propagated, choice A isincorrect.

When a business method that executes in the context of the local caller'stransaction throws a javax.ejb.EJBException, the EJB container isrequired to throw javax.ejb.TransactionRolledbackLocalException,as mentioned in Table 15 on page 375 of the EJB 2.0 specification. Therefore,choice B is correct.

Please refer to sections 18.2.2, 18.3.1, and 18.4.2.1 of the EJB 2.0 specificationfor further details (see Resources on page113 ).

Question 2:

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

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

Page 96 of 115 Java certification success, Part 3: SCBCD

Page 97: Java Certification Success, Part 3: SCBCD

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

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

Summary

This section provided a look at the effects of various exceptions and errorsencountered in EJB applications. We saw that application exceptions representerror conditions that the client expects and might be able to recover from, whilesystem exceptions indicate conditions that are unrecoverable. We also exploredthe container and bean provider's responsibilities when dealing with differentexceptions. It is important to be aware of the different exception types receivedby local and remote clients. Finally, we saw the details of the most commonapplication and system exceptions in EJB.

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

Java certification success, Part 3: SCBCD Page 97 of 115

Page 98: Java Certification Success, Part 3: SCBCD

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 theenterprise bean environment.

Environment entries are variables whose values are specified in the deploymentdescriptor and looked up by the bean using JNDI interfaces. Each enterprisebean defines its own set of environment entries. These values are read only atruntime.

The value of an environment entry is of the Java type declared by the BeanProvider in 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 declarationcontains the <env-entry> element. The environment entry values may be anyof the following Java types:

° String

° Character

° Integer

° Boolean

° Double

° Byte

° Short

° Long

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

Page 98 of 115 Java certification success, Part 3: SCBCD

Page 99: Java Certification Success, Part 3: SCBCD

° 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 entriesdeclared by the bean are set to meaningful values. The Deployer uses the toolsprovided by the container to create the environment entries that are declared inthe enterprise bean's deployment descriptor by the Bean Provider. He may setdifferent values for the enterprise bean environment entries for eachdeployment/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 localor remote.

The Bean Provider declares the EJB references in the deployment descriptorand looks up the home interface of the referenced enterprise bean in theenterprise bean's environment using JNDI. The Deployer binds the EJBreferences to the real JNDI names of the enterprise bean homes in the targetoperational 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 enterprisebeans be organized in the ejb sub-context of the bean's environment (that is, inthe "java:comp/env/ejb" JNDI context).

For example, the following elements in the deployment descriptor declare anEJB reference Emp within the subcontext ejb:

<entity>...<ejb-ref>

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

</ejb-ref>...

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

Java certification success, Part 3: SCBCD Page 99 of 115

Page 100: Java Certification Success, Part 3: SCBCD

</entity>

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

Context initCtx = new InitialContext();Object result = initCtx.lookup("java:comp/env/ejb/Emp");EmpHome empHome = (EmpHome)javax.rmi.PortableRemoteObject.narrow(result, EmpHome.class);

The Application Assembler can use the <ejb-link> element in thedeployment descriptor to link an EJB reference to a target enterprise bean. Thevalue of the <ejb-link> element in the referencing enterprise bean element isthe <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 mustbe defined in the <ejb-name> element of the target bean as shown:

<session><ejb-name>EmployeeRecord</ejb-name>...

</session>

The Deployer:

° Must ensure that all the declared EJB references are bound to the homes ofenterprise beans that exist in the operational environment

° Must ensure that the target enterprise bean is type-compatible with the typesdeclared for the EJB reference

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

Page 100 of 115 Java certification success, Part 3: SCBCD

Page 101: Java Certification Success, Part 3: SCBCD

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

Resource manager connection factories

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

The Bean Provider declares the resource manager connection factoryreferences in the deployment descriptor using the <resource-ref> elementand looks up the resource manager connection factory object using JNDI. Aresource manager connection factory reference is scoped to the enterprisebean whose declaration contains the <resource-ref> element, so therearen't any naming conflicts with other beans.

The standard resource manager connection factory types are:

° javax.sql.DataSource resource manager connection factory type: Forobtaining JDBC connections

° javax.jms.QueueConnectionFactory or thejavax.jms.TopicConnectionFactory: For obtaining JMS connections

° 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><res-sharing-scope>Shareable</res-sharing-scope>

</resource-ref>

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

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

Java certification success, Part 3: SCBCD Page 101 of 115

Page 102: Java Certification Success, Part 3: SCBCD

Container. 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 mappinginformation configured by the Deployer.

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

The following code sample illustrates obtaining a JDBC connection using 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> elementprovided by the Bean Provider to the actual JNDI name of the resourcemanager connection factory in the operational environment. If the value of the<res-auth> element is Container, the Deployer is responsible forconfiguring the sign-on information.

The system administrator adds, removes, and configures resource managers inthe EJB Server environment, and he is also in charge of giving them meaningfulJNDI names.

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 toadministered objects in the target operational environment.

The EJB specification recommends, but does not require, that all resourceenvironment references be organized in the appropriate subcontext of thebean's environment for the resource type (for example, in the

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

Page 102 of 115 Java certification success, Part 3: SCBCD

Page 103: Java Certification Success, Part 3: SCBCD

"java:comp/env/jms" JNDI context for JMS destinations).

We can declare the JMS destination in the deployment descriptor, as shownbelow:

<resource-env-ref><resource-env-ref-name> jms/ReservationQueue </resource-env-ref-name><resource-env-ref-type> javax.jms.Queue </resource-env-ref-type>

</resource-env-ref>

In the bean's business method, we can look up the object as illustrated below:

Context initCtx = new InitialContext();Object result = initCtx.lookup("java:comp/env/jms/ReservationQueue");javax.jms.Queue queue = (javax.jms.Queue)result;

Sample questions

Question 1:

Which of the following are valid Java types that the <env-entry-type>deployment descriptor element can contain?

Choices:

° A. java.lang.Integer° B. int° C. java.lang.Double° D. double° E. java.lang.Object

Correct choice:

A and C

Explanation:

The only Java types that are valid values for the <env-entry-type>deployment descriptor element are:

° java.lang.Byte

° java.lang.Short

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

Java certification success, Part 3: SCBCD Page 103 of 115

Page 104: Java Certification Success, Part 3: SCBCD

° 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 asthe type for an environment entry value.

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

Question 2:

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

Choices:

° A. <ejb-ref-name>° B. <ejb-ref-type>° C. <home>° D. <ejb-link>° E. <remote>

Correct choice:

D

Explanation:

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

° <ejb-ref-name>

° <ejb-ref-type>

° <remote>

° <home>

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

Page 104 of 115 Java certification success, Part 3: SCBCD

Page 105: Java Certification Success, Part 3: SCBCD

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

The <ejb-ref-name> element specifies the EJB reference name; its value isused in the enterprise bean code. The <ejb-ref-type> element specifies theexpected type of the enterprise bean -- session or entity. The <home> and<remote> elements specify the expected Java types of the referenced bean'shome and component interfaces.

The application assembler uses the optional <ejb-link> element to link anEJB reference to a target enterprise bean. The value of the <ejb-link>element must match with one of the <ejb-name> values of the targetenterprise bean.

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

Summary

One of the most special features of enterprise beans is the support forcustomizing the bean at deployment time without modifying the source code inany way. In the bean's unique environment, we learned how to configuredifferent things like environment entries, resource manager connectionfactories, enterprise bean references, and resource environment references.Using these declared references, the Bean Provider looks up the differentvariables or objects using JNDI interfaces.

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

Java certification success, Part 3: SCBCD Page 105 of 115

Page 106: Java Certification Success, Part 3: SCBCD

Section 15. Security management

Overview

Security management in EJB applications can be achieved in two ways:programmatically and declaratively. It is preferable to choose the declarativeway because you can customize the security policies through the deploymentdescriptor without altering the source code of the bean. However, wheninstance-level authorization is required, you need to make use of programmaticsecurity.

A security role is a logical role that a given type of user must belong to in orderto successfully use an application. Security roles are mapped to real worldusers and groups when the bean is deployed. Because you don't have to hardcode specific user identities into the bean code, it makes enterprise beans moreportable. You need to use security roles whether you are using declarative orprogrammatic authorization.

Programmatic security

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

Accessing caller information

The javax.ejb.EJBContext interface provides two methods that allow theBean Provider to access security information about the caller of an enterprisebean. The Bean Provider can invoke these methods only in the enterprisebean's business methods for which the container has a meaningful clientsecurity 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:

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

Page 106 of 115 Java certification success, Part 3: SCBCD

Page 107: Java Certification Success, Part 3: SCBCD

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

// perform secure tasks here}

}

private void checkUser() {Principal callerPrincipal = ejbContext.getCallerPrincipal();String callerName = callerPrincipal.getName();

// use the name in a database query}

Declaration of security roles referred in the bean code

The Bean Provider must declare each security role referenced in the code usingthe <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 roles

The role references, which are names hard coded by the Bean Provider, needto be mapped to the actual security roles defined by the Application Assembler.

This mapping is performed by the application assembler using the<role-link> element as shown below. The value of the <role-link>element must be the name of one of the security roles defined in a<security-role> element.

<security-role-ref><role-name<payroll</role-name><role-link>payroll-department</role-link>

</security-role-ref>

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

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

Java certification success, Part 3: SCBCD Page 107 of 115

Page 108: Java Certification Success, Part 3: SCBCD

as illustrated below:

<assembly-descriptor><security-role>

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

Declarative security

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

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

By specifying arguments using the <method-params> element, you candistinguish among different overloaded methods. We can differentiate amongmethods having the same name in the home or component interface by usingthe <method-intf> element -- values can be Remote, Home, Local, orLocalHome. These elements are illustrated below:

<method-permission><role-name>payroll-department</role-name><method>

<ejb-name>PayrollBean</ejb-name><method-intf>Local</method-intf><method-name>myMethod</method-name><method-params>

<method-param>String</method-param><method-params>

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

Page 108 of 115 Java certification success, Part 3: SCBCD

Page 109: Java Certification Success, Part 3: SCBCD

</method></method-permission>

The Application Assembler uses the <unchecked> element instead of a rolename in the <method-permission> element to indicate that a method shouldnot be checked for authorization. If the method permission relation specifiesboth the <unchecked> element for a given method and one or more securityroles, the method should not be checked for authorization.

The Application Assembler can use the <exclude-list> element to indicatethe set of methods that should not be called. If a given method is specified bothin the <exclude-list> element and in the method permission relation, theenterprise bean's security should be configured such that no access ispermitted 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 tospecify whether the caller's security identity should be used for the execution ofthe bean methods or whether some other identity must be used.

The value of the <security-identity> element is either<use-caller-identity> (the default) or <run-as>. You should specify 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 itscallers.

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

Java certification success, Part 3: SCBCD Page 109 of 115

Page 110: Java Certification Success, Part 3: SCBCD

The <use-caller-identity> value cannot be specified for MDB, becausethey don'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 theDeployer's job.

The Deployer must ensure that the assembled application is secure after it hasbeen deployed in the target operational environment. He also performs anytasks that have been left unfinished by the Application Assembler.

Sample questions

Question 1:

Which of the following statements about security management of enterprisebeans are correct?

Choices:

° A. The run-as identity applies to the enterprise bean as a whole.° B. The run-as identity can be specified for any method.° C. The run-as identity is usually specified using the <runas> element.° D. The run-as identity does not affect the identity of the bean's callers.

Correct choice:

A and D

Explanation:

Choice A is correct because the run-as identity always applies to the enterprisebean as a whole.

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

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

Page 110 of 115 Java certification success, Part 3: SCBCD

Page 111: Java Certification Success, Part 3: SCBCD

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 on page113 ).

Question 2:

Read the following code (assume that all references have been properlyinitialized):

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

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

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

Java certification success, Part 3: SCBCD Page 111 of 115

Page 112: Java Certification Success, Part 3: SCBCD

Choice B is incorrect because the application assembler is responsible fordefining the <security-role> elements and for linking them to the<security-role-ref> elements defined by the Bean Provider.

Note that another way to achieve the same result would be to assign the adminsecurity role to the getAdminPassword() method in a<method-permission> element.

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

Summary

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

We also discussed the two programmatic security control methods that areinvoked on the context of the enterprise bean.

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

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

Page 112 of 115 Java certification success, Part 3: SCBCD

Page 113: Java Certification Success, Part 3: SCBCD

Section 16. Wrap-up and resources

Summing up the tutorial

Preparing for a certification exam is quite different from learning the technology.Even if you are an experienced professional in the relevant field, your successin the exam is assured only if you follow a focused learning approach based onthe exam objectives. We hope that this tutorial helped to familiarize you with theexam objectives and the kind of questions asked.

To gain a deep understanding of the concepts, it is also necessary to getsufficient hands-on experience in all the areas covered by the exam. Werecommend that you try out the code fragments and deployment descriptorcustomization examples provided in the tutorial.

The SCBCD certification tests your competence in server-side componentdevelopment using the EJB technology. Success in this exam will definitelyboost your confidence level and give you a competitive edge in your career.

We hope that this tutorial has been effective in providing you a clear insight intothe exam objectives and preparing you for the certification.

Enjoy your studies and good luck with the exam!

Resources

° Download the EJB 2.0 Specifications(http://java.sun.com/products/ejb/docs.html#specs) .

° Get a good grounding in EJB technology from these tutorials:° Getting started with EJB technology (developerWorks, April 2003)° The four-part series, Introduction to container-managed persistence and

relationships, Part 1, Part 2, Part 3, and Part 4 (developerWorks, March2002 -July 2002)

° EJB 2.0 CMP Tutorial° Writing Enterprise Applications

° The following resources will help elevate your SCBCD competency:° Head First EJB by Kathy Sierra and Bert Bates (O'Reilly 2003)° Enterprise Java Beans -- 3rd Edition by Richard Monson-Haefel (O'Reilly

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

Java certification success, Part 3: SCBCD Page 113 of 115

Page 114: Java Certification Success, Part 3: SCBCD

2001)° Mastering Enterprise JavaBeans -- 2nd Edition by Ed Roman, Scott

Ambler, Tyler Jewell, and Floyd Marinescu (Wiley 2001)° An introductory article on SCBCD certification by the authors of this

tutorial.

° Practice and assess your knowledge level using the Whizlabs SCBCD ExamSimulator (http://www.whizlabs.com/products/scbcd/scbcd.html) .

° Get effective guidance and reinforce your concepts for the exam by enrollingin Whizlabs SCBCD Instructor-Led Online Training(http://www.whizlabs.com/scbcd/training.html) .

° Enhance your knowledge by participating in the JavaRanch SCBCDdiscussion forum.

° Here is a nice collection (http://www.valoxo.ch/jr/SCBCD_Links.html) ofadditional resources that you must explore.

° Browse a wide range of excellent titles at the developerWorks DeveloperBookstore (http://devworks.krcinfo.com/) .

° Find more resources related to the technologies discussed here on thedeveloperWorks Java technology zone(http://www.ibm.com/developerworks/java/) .

° Find out how you can become an IBM Certified Developer(http://www-1.ibm.com/certify/certs/adcdxmlrt.shtml) .

Your feedback

Colophon

This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorialgenerator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLTextension functions that convert an XML file into a number of HTML pages, a zip file, JPEGheading graphics, and two PDF files. Our ability to generate multiple text and binary formatsfrom a single source file illustrates the power and flexibility of XML. (It also saves ourproduction team a great deal of time and effort.)

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

Page 114 of 115 Java certification success, Part 3: SCBCD

Page 115: Java Certification Success, Part 3: SCBCD

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

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

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