Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
The exam was launched worldwide on August 25, 2003. The SCBCD
certification requires you to be a Sun Certified Programmer for the Java
platform (any edition).
The 14 exam objectives mainly deal with EJB technology basics, lifecycle and
behavior of different bean types, how the clients interact with the beans,
container-managed persistence (CMP), transactions, and security
management. The tutorial is organized according to the exam objectives, with
each section dedicated to a corresponding exam objective. In addition, we've
provided example code wherever necessary, and at the end of each section, we
have provided sample exam questions, which test the concepts discussed
under that objective. Each question includes detailed explanations about why a
choice is correct or incorrect.
Seema has been with Whizlabs for over two years, where she has co-authored
the Sun certification exam simulators. She is an experienced corporate trainer
and conducts instructor-led online training for the SCJP, SCWCD, and SCBCD
certification exams for Whizlabs. She is also the moderator of the Whizlabs
SCBCD discussion forum. You can reach her at seema@whizlabs.com.
Introduction
Enterprise JavaBeans (EJB) architecture is a server-side distributed component
model, which follows the "Write Once, Run Anywhere" philosophy of the Java
platform. EJB applications can be written once and then deployed on any
EJB-compliant server without any source code changes or recompilation. The
runtime behavior of the enterprise bean can be customized through the
deployment descriptor itself.
Entity beans provide object representation of data in the database. They can
allow shared access from multiple users. The entity, its primary key, and remote
reference can survive the crash of the EJB container.
EJB 2.0
Guaranteed features
EJB 2.0 technology has simplified the development and deployment of J2EE
applications to a great extent.
° Local component and home interfaces for session and entity beans
Provides a local client view and support for efficient, lightweight access to
enterprise beans from local clients.
° EJB Query Language (EJB-QL) for entity bean finder and select
methods
Provides a portable, vendor-neutral way to define queries for finder and
select methods.
Supported APIs
Any EJB 2.0 container is guaranteed to provide the following APIs:
Programming restrictions
You should avoid the following features in your EJB development to ensure you
build portable EJB components:
° You must not use read/write static fields. Using read-only (final) static fields
is allowed.
° You must not attempt the use of the AWT functionality to output information
to a display, or to input information from a keyboard.
° You must not attempt the use of the java.io package to access files and
directories in the file system.
° A bean may act as a network client (that is, it may make use of the
java.net.Socket class), but it may not act as a network server, and thus,
it must not use the java.net.ServerSocket class to accept remote
connections.
° You must not attempt to query a class to obtain information about the
declared members that are not otherwise accessible to the enterprise bean
because of the security rules of the Java language.
° You must not attempt to use the Reflection API to access information that
the security rules of the Java programming language make unavailable.
° You must not attempt to create a class loader; obtain the current class
loader; set the context class loader; set security manager; create a new
security manager; stop the JVM; or change the input, output, and error
streams.
° You must not attempt to set the socket factory used by ServerSocket,
Socket, or the stream handler factory used by URL.
° You must not attempt to obtain the security policy information for a particular
code source.
° You must not attempt to gain access to packages and classes that the usual
rules of the Java programming language make unavailable to the enterprise
bean.
° You must not attempt to access or modify the security configuration objects
(Policy, Security, Provider, Signer, and Identity).
° You must not attempt to use the subclass and object substitution features of
the Java Serialization protocol.
° You must not attempt to pass the this reference of the bean as an
argument or method result. The enterprise bean must pass the result of
SessionContext.getEJBObject(),
SessionContext.getEJBLocalObject(),
EntityContext.getEJBObject(), or
EntityContext.getEJBLocalObject() instead.
EJB roles
The EJB specification defines six distinct roles in the application development
lifecycle:
These roles have defined sets of responsibilities, and a single party may handle
more than one role:
Application Assembler
Combines multiple enterprise beans with other types of application
components (for instance, JSP components) to compose an application.
The Application Assembler delivers one or more ejb-jar files that contain
the enterprise beans along with their application assembly instructions.
Deployer
Takes one or more ejb-jar files produced by a Bean Provider or
Application Assembler and deploys them in a specific EJB container.
The Deployer delivers enterprise beans that have been customized for
the target operational environment. To perform their role, the Deployers
use tools provided by the EJB container.
System Administrator
The ejb-jar file must contain, either by inclusion or by reference, the class files
of each enterprise bean as follows:
The ejb-jar file must contain the deployment descriptor, stored with the name
ejb-jar.xml in the META-INF folder. The ejb-jar file must also contain, either by
inclusion or by reference, the class files for all the classes and interfaces that
each enterprise bean class and the home and component interfaces depend
upon, except J2EE and J2SE classes.
The ejb-jar file is not required to contain the manifest file. The stubs for remote
interfaces and classes implementing the component, home interfaces are
generated by the container and hence are not included in the ejb-jar file.
Sample questions
Question 1:
Which of the following must not be packaged in the ejb-jar file of an entity bean?
Choices:
Correct choice:
Explanation:
The ejb-jar file is the standard format for packaging enterprise beans and
assembled applications. It contains the XML deployment descriptor, the
enterprise bean classes, the enterprise bean remote and home interfaces, and
the primary key class (only for entity beans). The ejb-jar should also contain the
superclasses and superinterfaces of the above classes. It should also include
the dependent classes and the classes and interfaces used as method
parameters, return types, and exceptions. So choices A, B, C, and E are
incorrect.
To learn more about the ejb-jar file, refer to section 23 of the EJB 2.0
specification (see Resources on page113 ).
Question 2:
Which of the following are not allowed in enterprise beans according to the EJB
2.0 programming restrictions?
Choices:
Correct choice:
C, D, and E
Explanation:
The Bean Provider must follow some programming restrictions to ensure that
the enterprise bean is portable and can be deployed in all EJB 2.0 containers.
An enterprise bean must not use read/write static fields, however static fields
are allowed if they are made read-only by declaring them with the final
keyword. The bean must not attempt to load a native library; this restriction is to
avoid security holes. The enterprise bean must not manage threads or thread
groups because these functions are reserved for the EJB container.
For a complete list of the EJB 2.0 programming restrictions, please refer to
section 24.1.2 of the EJB 2.0 specification (see Resources on page113 ).
Summary
This section provided an overview of the EJB architecture and the different
types of enterprise beans. We discussed which features and APIs are
guaranteed to be supported by the EJB 2.0 specification, and you now know the
programming restrictions on EJB business methods to ensure that the bean is
portable and can be deployed in any compliant EJB 2.0 container. The
responsibilities of the different roles involved in the EJB development lifecycle
are spread over the remaining objectives. In this objective, we have simply
provided an overall picture of the responsibilities of each role.
A local client of a session bean is collocated in the same JVM as the bean.
Here, the local component and home interfaces provide the client view. The
local client view is not location-independent. The arguments and results of the
methods of the local interface and local home interface are passed by
reference.
Even though it is possible for a session bean to have a local view and a remote
view, typically a session bean provides only one of these.
CartHome cartHome =
(CartHome)javax.rmi.PortableRemoteObject.narrow(initialContext.lookup("ejb/cart"),
CartHome.class);
CartHome cartHome =
(CartHome)initialContext.lookup("java:comp/env/ejb/cart");
The home interface of a stateless session bean defines only one create
method, which does not take any arguments.
MyRemote bean1=myHome.create();
Handle handle=bean1.getHandle();
A local client can create a session object by invoking any one of the
create<METHOD> (...) methods, defined in the local home interface.
This method cannot be invoked by a client because session beans do not have
primary keys. As a consequence, local clients cannot remove a session bean by
calling any methods on the home interface of the session bean.
Local clients do not need an EJBMetaData interface because they can use
reflection to extract bean information. Also, handles are not required for local
clients because there aren't any stubs.
Component interface
The component interface exposes the business methods of the session object
to clients. The EJB Object, which implements this interface, delegates
invocation of a business method to the session bean instance.
° EJBHome getEJBHome()
° Handle getHandle()
° java.lang.Object getPrimaryKey()
° boolean isIdentical(EJBObject obj)
° void remove()
° EJBLocalHome getEJBLocalHome()
° java.lang.Object getPrimaryKey()
° boolean isIdentical(EJBLocalObject obj)
° void remove()
Stateless session beans created from the same home have the same identity
assigned by the container. For example:
When creating a stateful session bean, the EJB container assigns it a unique
identity because they hold the client conversational state. So two stateful
session bean instances created from the same home are not considered
identical. For example:
Sample questions
Question 1
Choices:
Correct choice:
B and C
Explanation:
Choice C is correct because the local and remote component interfaces provide
methods called getEJBLocalHome() and getEJBHome() that return the
local and remote home interfaces of the session bean, respectively.
Please refer to section 6.5 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Question 2:
Choices:
Correct choice:
Explanation:
Please refer to section 6.9 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
This section focused on the client view of the remote and local interfaces of
session beans. First, you learned how to perform a JNDI lookup to locate the
home object of a bean. It is important to note the differences in code for when
the home is remote and when the home is local. You also observed the details
of the methods in the home and component interfaces -- both local and remote.
Stateful session beans retain the conversational state of the client, while
Stateless session beans are dedicated to a client only for the duration of the
method call. Stateless session beans can have instance variables, but they
cannot preserve client data across multiple method invocations. All instances of
a particular type of stateless session bean are equivalent, so the container may
choose any available instance to serve a client method call. Two successive
client calls to a stateless session bean may be served by two different instances
of that session bean.
° void ejbActivate()
° void ejbPassivate()
° void ejbRemove()
° void setSessionContext(SessionContext ctx)
The ejbActivate() notification signals that the instance has just been
reactivated.
A client creates a session bean instance using one of the create <METHOD>()
methods defined in the session bean's home interface. The container calls the
ejbCreate<METHOD>() method whose signature matches that of the create
<METHOD>() method. Each stateful session bean class must have at least one
ejbCreate<METHOD>() method. The stateless session bean class can have
only one ejbCreate() method, which must not take any arguments.
// Home interface
// Remote interface
The Bean Provider should not store in a transient field a reference to any of the
following objects:
° SessionContext object
° Environment JNDI naming context and any of its subcontexts
° Home and component interfaces
° UserTransaction interface
The content of transient fields may be lost between the ejbPassivate and
ejbActivate notifications.
SessionContext interface
° getUserTransaction(): Returns a
javax.transaction.UserTransaction reference for use by session
beans with bean-managed transaction (BMT) demarcation.
SessionSynchronization interface
A stateful session bean with CMT demarcation may implement the
javax.ejb.SessionSynchronization interface to receive notifications
when a transaction starts, when it is about to end, and when it is over. These
notifications are helpful for the bean to perform database synchronization
operations.
BMT beans must not implement this interface, because they are themselves
responsible for demarcating transactions. Stateless session beans are not
allowed to maintain transactions across multiple methods, so they must not
implement this interface.
° Session bean's remote interface and remote home interface, if the session
bean provides a remote client view
° Session bean's local interface and local home interface, if the session bean
provides a local client view
° It may (but is not required to) implement the session bean's component
interface.
ejbCreate<METHOD>() methods
° The session bean class must define one or more
ejbCreate<METHOD>(...) methods in the case of stateful session beans,
and no more than one no-argument ejbCreate() method in the case of
stateless session beans.
Business methods
° The method names can be arbitrary, but they must not start with "ejb".
° The argument and return value types for a method must be legal types for
RMI/IIOP if the method corresponds to a business method on the session
bean's remote interface.
° The throws clause may define arbitrary application exceptions, but they
must not declare java.rmi.RemoteException.
Component interface
° The remote interface must extend the EJBObject interface and the local
interface must extend the EJBLocalObject interface.
° The methods defined in the remote interface must follow the rules for
RMI/IIOP.
° For each method defined in the interface, there must be a matching method
in the session bean's class.
° All the exceptions defined in the throws clause of the matching method of
the session bean class must be defined in the throws clause of the method
of the interface.
° The remote interface methods must not expose local home or component
interface types.
Home interface
° The remote home interface must extend the EJBHome interface and the local
home interface must extend the EJBLocalHome interface.
° The methods for a stateless session bean must be named create() and
ejbCreate().
The container must ensure that only one thread is executing an instance at any
time. If a client request arrives for an instance while the instance is executing
another request, the container may throw java.rmi.RemoteException to
the second request if the client is a remote client, or
javax.ejb.EJBException if the client is a local client.
Sample questions
Question 1:
Which of the following method declarations for a session bean class are valid?
Choices:
Correct choice:
A and B
Explanation:
A session bean class must declare one or more ejbCreate() methods that
must be prefixed with ejbCreate. Moreover, the method declaration must be
public, it must neither contain the final nor static modifiers, its arguments must
be legal RMI-IIOP types, the return type must be void (session beans hide their
identity, which is the main difference between them and entity beans!), and its
throws clause must contain the javax.ejb.CreateException as well as
arbitrary application exceptions. Thus, only choices A and B are correct.
Note that in the case of stateless session beans, the rules are more restrictive.
There must be exactly one method, it must be called ejbCreate, and it must
not take any arguments. The other rules mentioned above still apply.
Please refer to section 7.10.3 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Question 2:
Choices:
javax.ejb.EntityBean interface
° D. The ejbActivate() method
° E. Methods to create new session beans
Correct choice:
C and D
Explanation:
Note that the return type and the throws clause are not part of the signature of
a method.
Please refer to section 7.5.1 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
Thi section briefly covered the differences between stateful and stateless
session beans. We identified the methods defined in the SessionBean and
SessionContext interfaces. The significance of the
The following figure illustrates the lifecycle of a stateful session bean instance:
At first, the bean is in the Does-not-exist state. The client invokes the
create() method on the home of the bean. The container instantiates the
bean and invokes the setSessionContext() method, passing a
SessionContext instance. The bean is assigned to its EJB Object. The
container invokes the ejbCreate() method matching the create() method
invoked by the client. The reference to the EJB Object is returned to the client;
now the bean is in the Ready state.
If the client invokes the remove() method on the bean, the container invokes
ejbRemove() on the bean and moves out of the Ready state into the
Does-not-exist state. This can also happen when a bean times out in the Ready
state. Note that the bean cannot time out while in a transaction.
After serving the client, the bean is disassociated from the EJB Object and
returns to the Ready state. When the container no longer needs the instance,
the container invokes ejbRemove() on it.
° getUserTransaction() of SessionContext
Can be invoked from the ejbCreate() and ejbRemove() business
methods of beans with BMT demarcation.
° Methods of UserTransaction
Can be invoked only from business methods of beans with BMT
demarcation.
Sample questions
Question 1:
Which of the following events will result in a stateful session bean transiting to
the Does-not-exist state?
Choices:
Correct choice:
A, D, and E
Explanation:
Three ways exist for making a stateful session beans transit to the
Does-not-exist state. When either the bean is in the Ready state and a timeout
occurs (choice A) or the client invokes remove() on the component interface
of the bean (choice E), the EJB container invokes ejbRemove() on the bean
instance, which makes it transit to the Does-not-exist state.
Choice B is incorrect because when the EJB container passivates the bean
instance -- that is, it invokes the ejbPassivate() method on it -- the bean
goes from the method-ready state to the Passive state.
Choice D is correct because if a client invokes a method for which the access
has been denied by the EJB container, the EJB container throws a
java.rmi.RemoteException to a remote client and a
javax.ejb.EJBException to a local client. These are considered to be
system exceptions. When a system exception is thrown from any method of the
bean regardless of its current state, the bean goes to the Does-not-exist state.
Please refer to sections 7.6 and 21.6.9 of the EJB 2.0 specification for further
details (see Resources on page113 ).
Question 2:
Choices:
Correct choice:
D and E
Explanation:
Based on the question, it is clear that we are dealing with a stateful session
bean with a CMT demarcation because it defines the afterCompletion()
method of the javax.ejb.SessionSynchronization interface. BMT
session beans and stateless session beans are not allowed to implement that
interface.
Choice C is incorrect because the question states that the session bean defines
a remote client view. As a result, it is not allowed to invoke
getEJBLocalHome() on the SessionContext object. An
IllegalStateException is thrown by the container if it does.
Choice E is correct because the bean is allowed to perform JNDI lookups from
any instance method of the session bean class, except from constructors.
Please refer to section 7.6.1 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
This section addressed the details of stateless and stateful session bean
lifecycles. You must be able to arrange the various lifecycle events in the proper
order. Because stateless session beans do not maintain client state, their
lifetime is not controlled by the client, which makes the event flow different from
that of stateful beans. We also reviewed the operations that are allowed to be
performed from the various bean methods.
Overview
Entity beans allow their clients to access and manipulate data from a database
in an object-oriented manner. Multiple clients may access an entity object
concurrently. It is the responsibility of the container to synchronize the access
by means of transactions.
An entity bean may provide a remote client view, a local client view, or both.
While the remote client view is location dependent, the local client view is not.
However, to be the target of container-managed relationships (CMRs), entity
beans need to provide local interfaces.
While a crash of the JVM may result in a rollback of current transactions, it does
not destroy previously created entity objects nor does it invalidate the
references to the home and component interfaces held by clients.
Home interface
The home interface allows the client to create, find, and remove entity objects
within the enterprise bean's home as well as to execute home business
methods, which are not specific to a particular entity bean. For each entity bean
deployed in a container, the container provides a class that implements a home
interface for the entity bean.
The following code illustrates the definition of the remote home interface of an
entity bean.
° EJBMetaData getEJBMetaData()
° HomeHandle getHomeHandle()
The following code illustrates a client looking up a home object reference and
invoking one of the create methods:
° Every finder method in the home must have a matching method in the bean
class that starts with the prefix ejbFind.
The following code illustrates multiple finder methods defined in the remote
home interface of an entity bean.
After looking up the home object of the entity using JNDI, a client can invoke a
finder method as shown by the code fragment below:
Component interface
A client can access an entity object through the entity bean's component
interface, which defines the business methods callable by clients. An entity
bean's remote component interface must extend the javax.ejb.EJBObject
interface, and the local component interface must extend the
javax.ejb.EJBLocalObject interface. These interfaces define the methods
that allow the client to perform some useful operations on an entity object's
reference. The implementation for these methods is provided by the container.
Sample questions
Question 1:
Choices:
Correct choice:
A and D
Explanation:
A local client can access an enterprise bean using the bean's local interface
and local home interface. The EJBLocalObject interface does not define a
getHandle() method because the client and the enterprise bean are located
in the same EJB container. The Handle is a serializable reference, which allows
a remote client to obtain a reference to an enterprise bean on a remote node on
a network. Therefore, it is not necessary to get the Handle object in this case.
The EJBLocalObject interface does define methods to get the primary key
and to compare two local EJB Objects. So choices B and C are incorrect.
For more information, refer to section 6.5 of the EJB 2.0 specification (see
Resources on page113 ).
Question 2:
...
Choices:
° B. The return type of each create() method (that is, Car) must be the type
of the local component interface.
° C. The return type of each create() method (that is, Car) must be the type
of the remote component interface.
Correct choice:
C and E
Explanation:
beans, but not for stateless session beans, which must declare only one
create() method that is named "create" and that takes no arguments.
Therefore, choice E is correct while choice F is incorrect.
Please refer to sections 9.5 and 9.6 of the EJB 2.0 specification for further
details (see Resources on page113 ).
Summary
In this section, you learned the various ways in which clients interact with entity
beans. We saw the method types exposed by the home and component
interfaces and the rules for defining them.
Note the significance of home business methods and how they differ from the
business methods defined in the component interface. Handles are only for
remote clients while primary keys can be retrieved by both remote and local
clients.
The Bean Provider uses the deployment descriptor to specify the CMP fields
and CMR fields. The set of XML elements in the deployment descriptor
describing the CMP and CMR fields is known as the abstract persistence
schema of the entity bean. The Deployer maps the abstract persistence schema
of a set of interrelated entity bean classes into the physical schema used by the
underlying data store by using the container provider's tools.
° The CMP and CMR fields must be specified in the deployment descriptor
using the <cmp-field> and <cmr-field> elements respectively.
° Accessor methods must be defined in the bean class for the CMP and CMR
fields.
° Accessor methods must be public and abstract, named with the first letter of
the name of the CMP or CMR fields in uppercase, and prefixed by get or
set.
° The accessor methods for a CMR field must be defined in terms of the local
interface of the related entity bean.
° The Java types assigned to the CMP field are restricted to primitive types
and serializable types.
° There must be no set accessor methods defined for the primary key CMP
fields in the component interface of the entity bean.
° Accessor methods and collection classes for CMR fields must not be
exposed through the remote interfaces.
Note that the CMP fields are not declared as instance variables. Instead we
have defined abstract accessor methods for the container-managed fields,
which map to actual database columns. The fields need to be specified in the
deployment descriptor using <cmp-field> elements, as shown below:
...
<entity>
<ejb-name>CourseBean</ejb-name>
<local-home>CourseHome</local-home>
<local>Course</local>
<ejb-class>example.cmp.basic.CourseBean</ejb-class>
<prim-key-class>String</prim-key-class>
<primkey-field>courseId</primkey-field>
<persistence-type>Container</persistence-type>
<cmp-version>2.x</cmp-version>
<reentrant>False</reentrant>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>trainer</field-name>
</cmp-field>
</entity>
...
CMP relationships
CMRs are defined in terms of the local interfaces of the related entity beans.
Relationships may be one-to-one, one-to-many, or many-to-many relationships,
and may be either bi-directional or unidirectional. An entity bean that does not
have a local interface can have only unidirectional relationships from itself to the
other entity beans.
<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>
Assigning relationships
When we reassign relationships, the container ensures that data integrity is
maintained by using the multiplicity defined for both beans. Consider the
following relationships between instances of Employee and Address entity
beans.
It is not possible to share a single Address bean between two Employee beans
because they share a one-to-one relationship.
Here the "Address 1" object reference was moved from "Employee A" to
"Employee B."
Note that in this case, the "Department 1" object reference is shared between
Employee A, B, and C, instead of being moved.
Cascade deletes
The removal of an entity object can cause the removal of a related entity object,
if the <cascade-delete> element is specified for the target bean. The entity
that uses the <cascade-delete> element must have a multiplicity of "One" in
the relationship. The container calls the ejbRemove() method on the target
bean instance due to the cascade delete operation and then removes its data
from the database.
<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>
<ejb-relationship-role>
<ejb-relationship-role-name>Profile</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<cascade-delete/>
<relationship-role-source>
<ejb-name>ProfileEJB</ejb-name>
</relationship-role-source>
</ejb-relationship-role>
</ejb-relation>
Sample questions
Question 1:
What are the valid types for the CMR field of an entity bean?
Choices:
° A. Primitive types
° B. Collection
° C. Set
° D. Entity bean's local interface
° E. java.lang.String
° F. java.lang.Integer
Correct choice:
B, C, and D
Explanation:
The get() method for a CMR field in the entity bean class must return either
the local interface of the entity bean or a collection (either
java.util.Collection or java.util.Set) of the same, so these are the
valid types of CMR fields of an entity bean. The set() method for the
relationship must take as an argument the entity bean's local interface or a
collection of the same.
For more information, refer to section 10.3.2 of the EJB 2.0 specification (see
Resources on page113 ).
Question 2:
There are two entity beans, BeanA and BeanB, in a one-to-one unidirectional
relationship. In addition, there are two references, ba1 and ba2, to instances of
BeanA and two references, bb1 and bb2, to instances of BeanB. Moreover,
ba1 is linked to bb1 and ba2 is linked to bb2. If the statement
ba1.setBean2(ba2.getBean2()) is executed, which of the following
expressions will be true?
Choices:
° A. ba2.getBean2() != null
° B. ba2.isIdentical(bb1.getBean1())
° C. bb1.isIdentical(ba2.getBean2())
° D. bb2.isIdentical(ba1.getBean2())
° E. ba1.isIdentical(bb2.getBean1())
° F. ba1.getBean1() == null
Correct choice:
Explanation:
First, let's examine what the relationships look like. We have two entity beans,
Bean1 and Bean2, in a one-to-one unidirectional relationship. This means that
one instance of Bean1 has a reference to one instance of Bean2, but the
instance of Bean2 has no reference to the instance of Bean1. As the question
states, ba1 is linked to bb1 and ba2 is linked to bb2.
Choice C is incorrect because after the execution of the above statement, ba2
does not refer to any instance of Bean2. Thus, ba2.getBean2() returns null.
Choice D is correct because after the execution of the above statement the
instance of Bean2 (bb2) that was previously referenced by ba2 is now
referenced by ba1. Thus, this expression returns true.
Please refer to section 10.3.7.2 of the EJB 2.0 specification for further details
(see Resources on page113 ).
Summary
This section examined how to write CMP entity beans and describe their
container-managed fields in the deployment descriptor. We discussed the rules
and semantics to be followed when defining CMRs between entity beans, and
we saw how the multiplicity defined for the relationship participants is significant
when assigning bean relationships. Finally, you also learned how the removal of
an entity bean can be cascaded to cause the removal of related entity beans.
Overview
CMP entity beans support instance pooling, just like stateless session beans.
They are also passivated and activated, but unlike the stateful session beans,
the bean state is not serialized.
The container interacts with the database when a new entity is to be created or
deleted. Similarly, it manages the transactions and the synchronization of the
bean state with the database. Let's examine the important events in the life of
an entity bean instance and how the container interacts with the bean during
these events.
State diagram
The state diagram of a CMP entity bean is shown below:
Lifecycle events
The bean can be in one of the following states:
° Does-not-exist
° Pooled
° Ready
At first, the bean is in the Does-not-exist state. The bean has not yet been
instantiated. The container instantiates the bean by calling the
Class.newInstance() method on the bean class. Then an
EntityContext object is passed by invoking the setEntityContext()
method. Now the bean instance is in the Pooled state. In this state, the bean
instance can service finder methods, select methods, and home business
methods, because they do not require the bean to have an identity. The bean
instance can service entity-specific client calls when it is in the Ready state.
Two possible transitions from the Pooled to the ready state exist: through the
ejbCreate<METHOD>(...) and ejbPostCreate<METHOD>(...) methods,
or through the ejbActivate() method. The container might decide to remove
a bean from the pool and allow it to be garbage collected. At this point, the
unsetEntityContext() method is called on the bean instance.
Let's discuss the different events involved in the state transitions of a bean
instance.
home.
° The container makes an EJB Object and returns its reference to the client.
° The bean instance remains in the Pooled state.
Client invokes the remove() method on the bean's EJB Object or EJB
home
° The ejbRemove() method is invoked on the bean instance.
° The entity data is removed from the database.
° The EJB Object reference is invalidated.
° The bean instance enters the Pooled state.
setEntityContext()
The entity object identity is not available in the setEntityContext() method.
The programmer can use this method to allocate any resources that are to be
held by the instance for its lifetime.
unsetEntityContext()
The container invokes this method when the container wants to reduce the
number of instances in the pool. After this method completes, the container
must not reuse this instance. The programmer can use this method to free any
resources that are held by the instance.
ejbCreate<METHOD>()
The container invokes the ejbCreate<METHOD>() methods when a client
invokes a matching create<METHOD>() method on the entity bean's home
interface. The Bean Provider can use this method to initialize the instance in
this method from the input arguments. He must not attempt to modify the values
of CMR fields in this method because the primary key is not yet available. This
method should return null. The ejbCreate<METHOD>>() methods and the
subsequent database insertion operations execute in the same transaction
context as the create<METHOD>() methods previously invoked.
ejbPostCreate<METHOD>()
The ejbPostCreate<METHOD>() methods have the same set of arguments
as the corresponding ejbCreate<METHOD>() methods, but their return type is
void.
ejbActivate()
The ejbActivate() method is invoked on an entity bean instance after
activation. The primary key of the associated entity object is available to the
instance during this method. The bean can use this method to acquire
additional resources that it needs while it is in the Ready state. The container
invokes this method within an unspecified transaction context.
ejbPassivate()
The ejbPassivate() method is invoked when the container decides to
disassociate the instance from an entity object identity. The primary key of the
associated entity object is available to the instance during this method. The
bean can use this method to release the resources that it acquired during the
ejbActivate() method. The container invokes this method within an
unspecified transaction context.
ejbRemove()
The ejbRemove() method is invoked in response to a client-invoked remove
operation on the entity bean's home or component interface or as the result of a
cascade-delete operation.
The container synchronizes the state of the instance before it invokes the
ejbRemove() method.
The entity bean identity is available during this method. After ejbRemove()
returns, the container removes the entity bean instance from all the
relationships in which it participates and then removes its persistent data. The
ejbRemove() method and the database delete operations are performed in
the transaction context of the invoked remove() method. The bean instance is
in the Ready state when ejbRemove() is invoked and it will be entered into the
pool when the method completes.
ejbLoad()
The ejbLoad() method is called when the container needs to synchronize the
state of an enterprise bean instance with the entity object's persistent state.
This method can be used to recompute or initialize the values of any instance
variables that depend on the entity bean's persistent state.
ejbStore()
The ejbStore() method is called when the container needs to synchronize
the state of the entity object in the database with the state of the enterprise
bean instance. This method is invoked in the same transaction context as the
previous ejbLoad() or ejbCreate() method invoked on the instance.
The Bean Provider can use the ejbStore() method to update the instance
using the accessor methods before its persistent state is synchronized.
ejbFind<METHOD>()
The ejbFind<METHOD>() methods are generated at the entity bean
deployment time using the container provider's tools. The container invokes the
ejbFind<METHOD>() method on an instance when a client invokes a
matching find<METHOD>() method on the bean home. The method is invoked
on a pooled entity instance, which remains pooled even after the method call.
This method is invoked in the transaction context of the matching
find<METHOD>() method.
ejbSelect<METHOD>()
The ejbSelect<METHOD>() methods are not directly exposed to the client in
the home or component interface because they are for the internal use of the
bean. They are declared as abstract by the bean provider and their
implementation is generated at deployment time using the container provider's
tools. These methods are typically called within a home or business method.
They execute in the transaction context determined by the transaction attribute
of the invoking method.
ejbHome<METHOD>()
The ejbHome<METHOD>() methods are invoked when the container selects
the instance to execute a matching client-invoked home business method. The
pooled instance, which is chosen for the method execution, remains in the
pooled state after the execution of the home method. It is invoked in the same
transaction context as the triggering home method. The entity Bean Provider
provides the implementation of the ejbHome<METHOD>(...) method. as an
EJB-QL expression in the deployment descriptor. Because the bean identity is
not available within this method, the bean must not attempt to access its
persistent state or relationships using the accessor methods.
Sample questions
Question 1:
Select all the methods of an entity bean class that have a matching method in
their home interface.
Choices:
° A. ejbCreate<METHOD>()
° B. ejbSelect<METHOD>()
° C. ejbLoad<METHOD>()
° D. ejbRemove<METHOD>()
° E. ejbFind<METHOD>()
Correct choice:
A and E
Explanation:
Please refer to sections 10.5.2 and 10.5.3 of the EJB 2.0 specification for
further details (see Resources on page113 ).
Question 2:
Choices:
° A. ejbRemove()
° B. ejbPassivate()
° C. unsetEntityContext()
° D. finalize()
Correct choice:
Explanation:
The ejbRemove() method is invoked when the client application invokes the
remove() method on the bean's EJBObject or EJBHome. It notifies the entity
bean instance that its data is about to be removed from the database. The bean
then transitions into the Pooled state. So choice A is incorrect.
The finalize() method should not be used to release the resources because
it might not be called at all. Hence, choice D is incorrect.
For more information, refer to section 10.5 of the EJB 2.0 specification (see
Resources on page113 ).
Summary
This section traced the lifecycle of a CMP entity bean. We have seen that
creation, passivation, activation, and removal of entity beans are significantly
different from that of session beans. You should be aware of the exact
sequence of events for each state transition of the bean instance.
We also discussed the methods defined in the bean class and the
responsibilities of the Bean Provider and container in each case.
EntityContext interface
The EntityContext interface allows an entity bean instance to access its
container-provided runtime context. After a bean instance is created, the
container invokes the setEntityContext() method on the instance, passing
a reference to its EntityContext. As the bean instance is switched between
EJB Objects by the container, the information obtained from EntityContext
(such as the primary key) is subject to change.
EntityContext methods
Let us examine the methods that can be invoked by the entity bean on its
EntityContext reference.
the method.
° javax.transaction.UserTransaction getUserTransaction(),
which returns an instance of a javax.transaction.UserTransaction
interface. Entity bean instances must not call this method because they do
not support BMT demarcation.
Primary keys
A primary key is an object that uniquely identifies an entity bean within its EJB
home. If two entity EJB Objects from the same home have the same primary
key, they are considered identical.
A primary key can be of two types: Single field keys or composite keys. A single
field primary key maps to a single persistence field in the entity bean. A
composite primary key maps to more than one persistence field in the entity
bean.
For example, we have the "custId" CMP field as the primary key for the
CustomerBean entity bean shown below:
<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>
Sample questions
Question 1:
Select all the methods in which the identity of an entity bean is not available.
Choices:
° A. ejbHome<METHOD>()
° B. ejbRemove()
° C. ejbCreate<METHOD>()
° D. ejbLoad()
° E. setEntityContext()
Correct choice:
A C, and E
Explanation:
Saying that the identity of an entity bean is available amounts to saying that the
getEJBObject(), getEJBLocalObject(), and getPrimaryKey()
methods can be successfully invoked (that is, without throwing an exception) on
the entity context object.
Please refer to section 10.5.5 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Question 2:
What are the requirements for a primary key class that maps to multiple fields of
an entity bean class?
Choices:
° A. The primary key class must be private and be an inner class of the
° B. The primary key class must be public and abstract because the
container will be responsible for providing an implementation of the primary
key classes.
° C. All fields of the primary key class must follow the JavaBeans conventions
-- that is, the fields must be private, and public accessor or mutator methods
must be provided.
° D. All fields of the primary key class must be declared public (and thus
break the encapsulation of the primary key class).
° F. ba1.getBean1() == null
Correct choice:
D and E
Explanation:
Choice A is incorrect because the primary key class must be declared public
and not private.
Choice B is incorrect because the primary key class does not need to be
declared abstract. The container should be allowed to use the primary class
without having to extend it.
Choice E is also correct because the primary key class is not allowed to declare
fields having names that are different from the names of the container-managed
fields declared in the <cmp-field> elements in the deployment descriptor.
Please refer to section 10.8 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
This section covered the methods defined in the EntityContext interface,
which is the interface the entity bean instance uses to interact with the
container. Some operations may require a valid transaction context or security
context to be available when they are invoked, while some others might work
only for CMTs. Hence, it is important to understand which operations are
allowed to be performed within each callback method of the bean and why.
We also discussed the rules regarding the primary keys of entity beans and how
to define the single field and composite keys.
Purpose of EJB-QL
EJB-QL is a query specification language for the finder and select methods of
CMP entity beans. This language is portable across databases and data
schemas. It is possible to parse and validate EJB-QL queries before entity
beans are deployed because the language is defined in terms of the abstract
persistent schema of the entity beans. These queries are written by the entity
Bean Provider in the deployment descriptor. Container tools then translate
these queries into the target language of the underlying data store.
° As queries for selecting entity objects through finder methods defined in the
home interface
° As queries for selecting entity objects or other values derived from an entity
bean's abstract schema type through select methods defined on the entity
bean class
Using EJB-QL
Basic syntax
EJB-QL also allows SELECT clauses to return CMP or CMR fields. Paths can
navigate over one or more CMR fields to end at either a CMR or CMP
single-valued field. In the example below, name is a CMP field, and address is
a CMR field that contains the city CMP field:
Note that path expressions cannot navigate beyond CMP fields. The following
query is invalid because city is a CMP field of the Address bean:
Conditional expressions
We can use conditional expressions in the WHERE clause to restrict the results
of the query.
Likewise, the following query returns only the customers who have placed
orders:
Here the age and name of the customer are passed as parameters to the query.
The DISTINCT keyword is used to specify that duplicate values must be
eliminated from the query results.
BETWEEN expressions
The BETWEEN clause is used to specify a range of values. It may be used only
on numeric primitives and their wrappers. It is inclusive of the upper and lower
limits.
The following query returns all the customers between the ages of 20 and 30:
IN expressions
The IN operator in the WHERE clause tests for membership in a list of literal
string values:
Here, the first query returns the customers from the given states and the second
returns those who are not from these states.
LIKE expressions
The LIKE operator allows you to select CMP String fields that match a given
pattern. The "%" symbol stands for any sequence of characters, while the "_"
symbol stands for a single character.
The query returns customers whose phone numbers are "453" and "45993," but
not "4534":
The following query returns a customer whose name is "rose," but not "roose."
<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>
It is declared as abstract in the entity bean class and can return values that
correspond to any CMP or CMR field type. Like find methods, select methods
can declare zero or more arguments. An ejbSelect() method definition is
shown in the following example:
The select methods are not declared in the home interfaces, so the
ejbSelect() method names in the bean class are mapped to the queries.
<query>
<query-method>
<method-name>ejbSelectAll</method-name>
<method-params/>
</query-method>
<result-type-mapping>Remote</result-type-mapping>
<ejb-ql>
SELECT OBJECT(a) FROM Address a
</ejb-ql>
</query>
Sample questions
Question 1:
Select all the expressions that are semantically equivalent to the BETWEEN
Choices:
Correct choice:
Explanation:
In EJB-QL, BETWEEN expressions always include the values at the limits. In this
case, BETWEEN 20 and 25 really means any values between 20 and 25, both
inclusive. Therefore, the only correct choice is D.
Please refer to section 11.2.7.7 of the EJB 2.0 specification for further details
(see Resources on page113 ).
Question 2:
Choices:
° A. EJB-QL queries are portable across databases, data schemas, and EJB
containers.
° B. EJB-QL queries can be used to insert records into the database.
° C. The SELECT clause must not use the OBJECT operator to qualify path
expressions.
° D. SELECT clauses may return a single or collection-based CMR field.
Correct choice:
A and C
Explanation:
EJB-QL uses the abstract persistence schema of entity beans, including their
relationships, for its data model. This makes the queries portable across EJB
containers.
At deployment time, the EJB-QL statements are translated into native data
access code, so they are independent of the underlying data store structure and
schema. Thus, choice A is correct.
EJB-QL queries can only fetch data from the database; they cannot be used for
updates and insertions. So choice B is incorrect.
EJB-QL allows SELECT clauses to return any CMP or single CMR field.
However, the path expressions in these clauses must not end with a
collection-based relationship field. So choice D is incorrect.
For more information, refer to section 11 of the EJB 2.0 specification (see
Resources on page113 ).
Summary
This section demonstrated how to use EJB-QL queries to access the data
required by the finder and select methods of an entity bean. We discussed the
correct and incorrect syntaxes for an EJB-QL query and how to define such
queries in the deployment descriptor. We reviewed how the results of the query
can be restricted using conditional expressions, BETWEEN expressions, LIKE
expressions, and comparison expressions.
Message-driven beans
Message-driven beans (MDBs) are asynchronous JMS message consumers.
They do not have home or component interfaces because clients never call
them directly. A client accesses it by sending messages to the JMS destination
(Queue or Topic) to which the bean listens. The client does not need to wait for
the bean instance to receive the message or process it. After sending the
message, the client can continue doing its job. However, there is no guarantee
that the bean will receive the messages in the same order in which they have
been sent.
MDB lifecycle
The lifetime of an MDB instance is controlled by the container. Only two states
exist: Does not exist and Ready, as illustrated in the following figure:
When a message arrives for the bean, the container invokes the onMessage()
method of one of the available instances, passing a Message object in
argument. Messages can be consumed and processed concurrently by using
MessageDrivenBean
The MessageDrivenBean interface defines lifecycle event notification
methods invoked by the container on the bean instance.
The ejbRemove() method is called at the end of the bean lifecycle, before it is
garbage collected.
MessageListener
A MessageListener object is used to receive asynchronously delivered
messages.
MessageDrivenContext
The MessageDrivenContext interface gives the MDB instance access to the
instance's runtime context maintained by the container. The context object
remains associated with the instance for the lifetime of the instance. This
interface contains only methods inherited from EJBContext.
Durable topic subscriptions, as well as queues, ensure that messages are not
missed even if the EJB server is not running. The
<subscription-durability> element specifies whether a JMS topic
subscription is intended to be durable or non-durable.
<message-driven>
<display-name>My Message Driven Bean</display-name>
<ejb-name>Mdb1</ejb-name>
<ejb-class>MyMDB</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<destination-type>javax.jms.Topic</destination-type>
<subscription-durability>NonDurable</subscription-durability>
</message-driven-destination>
</message-driven>
° The throws clause must not contain any application exception types.
The container may generate additional classes when the MDB is deployed.
Sample questions
Question 1:
Choices:
° A. getCallerPrincipal()
° B. getEJBHome()
° C. getRollbackOnly()
° D. isCallerInRole()
Correct choice:
Explanation:
For more information, refer to section 15.4.3 of the EJB 2.0 specification (see
Resources on page113 ).
Question 2:
Choices:
° A. MessageDrivenObject
° B. MessageDrivenBean
° C. MessageListener
° D. MessageDrivenContext
° E. MSListener
Correct choice:
B and C
Explanation:
Only Mandatory and Never may cause the EJB container to throw an
exception, so the remaining options are incorrect.
For more information, refer to section 15.4 of the EJB 2.0 specification (see
Resources on page113 ).
Summary
This section covered message-driven beans. The main point to remember
about MDBs is that they do not expose a client view. Therefore, their lifecycle is
entirely controlled by the container, they do not have component or home
interfaces, and the methods that can be invoked on the
MessageDrivenContext are limited. Also note that MDB methods must not
throw application exceptions, because there aren't any clients to handle them.
For this objective, we do not need to know much about the Java Messaging
Service, but it is necessary to be aware of the MDB configuration elements in
the deployment descriptor.
Overview
Transactional systems ensure that a unit of work either fully completes or is fully
rolled back. The EJB architecture supports distributed transactions, but not
nested ones. In nested transactions, a new transaction can be started, while a
transaction is currently active.
A session bean or an MDB can use BMT or CMT, but not both at the same
time. An entity bean can use only CMT.
Container-managed transactions
The EJB container is responsible for managing transaction boundaries in the
case of a CMT bean. When a client calls a method on an enterprise bean, the
new method can run in the caller's transaction, start a new transaction, or run
without a transaction. The action taken by the EJB container in this case is
decided by the transaction attribute defined for the method.
In the following example, all the methods of CustomerEJB have been given the
transaction attribute Required, except the addBonus() method, which has
been given the attribute Mandatory:
<enterprise-beans>
<session>
<ejb-name>CustomerEJB</ejb-name>
...
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CustomerEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>CustomerEJB</ejb-name>
<method-name>addBonus</method-name>
</method>
<trans-attribute>Mandatory</trans-attribute>
</container-transaction>
</assembly-descriptor>
MDBs must not throw application exceptions, because they don't have any
client view and they run asynchronously.
<method>
<ejb-name>CustomerEJB</ejb-name>
<method-name>addBonus</method-name>
<method-params>
<method-param> int </method-param>
</method-params>
</method>
Bean-managed transactions
In the case of BMTs, the bean itself manages transactions programmatically in
the business methods. The Bean Provider uses the
javax.transaction.UserTransaction interface to explicitly demarcate
transactions. A bean instance that starts a transaction must complete the
transaction before it starts a new one.
...
UserTransaction ut = ejbContext.getUserTransaction();
ut.begin();
method1();
method2();
...
if(someSuccessCondition)
ut.commit();
else
ut.rollback();
A bean can also look up the UserTransaction object from the JNDI ENC, as
shown below:
UserTransaction t = (UserTransaction)
jndiContext.lookup("java:comp/UserTransaction");
A stateful session bean instance may, but is not required to, commit a started
transaction before a business method returns. A stateless session bean
instance must commit a transaction before a business method returns, because
the same instance is not dedicated for multiple method calls. An MDB instance
must commit a transaction before the onMessage() method returns.
Methods of UserTransaction
The UserTransaction interface defines the following methods that are
invoked by the bean to manage the transactions:
° void rollback(): Rolls back the transaction associated with the current
thread.
Sample questions
Question 1:
Which of the following statements about transactions in EJB 2.0 are true?
Choices:
transaction attributes.
° B. Nested transactions are supported for BMT enterprise beans.
° C. Isolation levels can be specified for CMT session beans.
° D. A BMT MDB must begin and end a transaction within the onMessage()
method.
° E. If the transaction attribute of a bean method is Mandatory and a remote
client invokes it without a transaction, a
TransactionMandatoryException is thrown.
Correct choice:
A and D
Explanation:
Nested transactions and isolation levels are not supported in EJB 2.0, so
choices B and C are incorrect.
A BMT MDB must begin and end a transaction within the onMessage()
method -- that is, a transaction cannot span multiple method calls. So choice D
is correct.
Question 2:
Which of the following transaction attributes may cause the container to throw
an exception whenever the transaction context does not satisfy their
requirements?
Choices:
° A. Required
° B. RequiresNew
° C. Never
° D. Mandatory
° E. Supports
° f. NotSupported
Correct choice:
C and D
Explanation:
The transaction attribute Mandatory behaves the same way as the Required
attribute when a client calls with a transaction context. However, if the client
makes a call in an unspecified transaction context, the EJB container is required
to throw the javax.transaction.TransactionRequiredException
exception if the client is a remote client or the
javax.ejb.TransactionRequiredLocalException if the client is a local
client.
The transaction attribute Never behaves the same way as the NotSupported
attribute when a client calls without a transaction context. However, if the client
makes a call within a transaction context, the EJB container is required to throw
the java.rmi.RemoteException if the client is a remote client or the
javax.ejb.EJBException if the client is a local client.
Only Mandatory and Never may cause the EJB container to throw an
exception, so the remaining options are incorrect. Therefore, C and D are
correct, while A, B, E, and F are incorrect.
Please refer to section 17.6.2 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
In this section, we discussed the effect of CMT demarcation as compared to
that of BMTs in enterprise beans. It is important to remember that entity beans
must not use BMT demarcation. Similarly, we saw which transaction attributes
are applicable for MDBs, beans implementing SessionSynchronization
interfaces, and so on. For each bean type, we need to be aware of the methods
for which transaction attributes must be specified. Finally, we showed you the
significance of the UserTransaction() methods, which enable BMT beans
to programmatically manage transactions.
Application exceptions
An application exception is an exception defined in the throws clause of a
method in the bean's home or component interface. An application exception
class must be a direct or indirect subclass of java.lang.Exception, but
neither of java.lang.RuntimeException nor
java.rmi.RemoteException.
System exceptions
A system exception is an exception that the client does not expect or is not
expected to recover from. All unchecked exceptions as well as
java.rmi.RemoteException belong to this category. System-level errors
may be encountered during the execution of a session or an entity bean
business method, an MDB onMessage() method, or a container callback
method. Some examples include:
When system exceptions are detected, the container will automatically roll back
the existing transaction, if any. The bean instance will be discarded and the
exception will be logged.
exceptions are thrown. Let's examine these in detail for different situations.
Application exceptions
If the bean method is running in the context of the caller's transaction, the
container re-throws the exception to the client. The client can continue working
with the transaction but cannot commit the transaction if the bean instance has
invoked the setRollbackOnly() method. This situation does not arise in the
case of beans using BMT demarcation because transactions cannot propagate
into a BMT bean.
MDBs must not throw application exceptions, because they don't have any
client view and they run asynchronously.
System exceptions
For all bean types, system exceptions are logged, the existing transaction is
marked for rollback, and the bean instance is discarded.
The container does not throw any exception in the case of MDBs, because they
do not have any client view.
Application exceptions
° If a business logic exception occurs in the bean code, the Bean Provider
must throw it to the container as the appropriate application exception.
Accordingly, the application exception must be declared in the throws clause
of the business method in the component interface.
° If the Bean Provider catches an application exception and figures out that
the transaction cannot be committed, he calls
EJBContext.setRollbackOnly() for CMT beans or
UserTransaction.setRollbackOnly() for BMT beans, before
re-throwing the exception further.
° The Bean Provider must ensure that the bean instance is in a state such that
a client's attempt to continue and/or commit the transaction does not result in
the loss of data integrity.
System exceptions
° If the bean method encounters a RuntimeException or error, it should
simply propagate the error to the container.
° CreateException
° DuplicateKeyException
° RemoveException
° FinderException
° ObjectNotFoundException
CreateException
This exception can be thrown by the container to indicate a problem during the
bean creation. This method must be declared in the throws clauses of all the
create methods declared in an enterprise bean's home interface and all the
ejbCreate<METHOD>() methods declared in the enterprise bean's class.
DuplicateKeyException
The javax.ejb.DuplicateKeyException exception is thrown if an entity
object cannot be created because an entity with the same key already exists.
This exception is thrown by the create methods defined in an entity bean's
home interface. It is a subclass of javax.ejb.CreateException.
RemoveException
The javax.ejb.RemoveException exception may be thrown when
attempting to remove a bean when the enterprise bean or the container does
not allow it to be removed.
FinderException
The finder methods of an entity bean throw this exception to report a failure
when finding the requested entity (or entities). It must be included in the throws
clause of every finder method of the entity bean's home interface.
ObjectNotFoundException
The javax.ejb.ObjectNotFoundException exception is thrown by a
single-entity finder method to indicate that the specified entity does not exist. It
is a subclass of javax.ejb.FinderException.
° EJBException
° IllegalStateException
° NoSuchEntityException
° TransactionRequired(Local)Exception
° TransactionRolledback(Local)Exception
EJBException
The javax.ejb.EJBException exception is thrown by the bean to the
container to report that the invoked business or callback method could not
complete successfully because of some unexpected error. The container may
throw it to local clients when it catches a system exception. It is a subclass of
java.lang.RuntimeException.
IllegalStateException
This exception is also a subclass of java.lang.RuntimeException. The
container throws this exception to the enterprise bean to signal that a method
has been invoked at an illegal or inappropriate time, like calling
setRollbackOnly() within a method executing in an unspecified transaction
context.
NoSuchEntityException
The javax.ejb.NoSuchEntityException exception is thrown by an entity
bean instance to report that the referenced entity was removed from the
database. This exception may be thrown by ejbLoad(), ejbStore() and any
business methods. It is a subclass of javax.ejb.EJBException.
TransactionRequiredException/TransactionRequiredLocalException
If a bean method marked with the Mandatory transaction attribute is invoked
by a non-transactional client method,
javax.transaction.TransactionRequiredException is thrown if the
client is remote and javax.ejb.TransactionRequiredLocalException
is thrown if the client is local. TransactionRolledbackException is a
subclass of java.rmi.RemoteException and
TransactionRolledbackLocalException is a subclass of
javax.ejb.EJBException.
TransactionRolledbackException/TransactionRolledbackLocalException
If a client receives
javax.transaction.TransactionRolledbackException or
javax.ejb.TransactionRolledbackLocalException, the client knows
for certain that the transaction has been marked for rollback.
TransactionRolledbackException is a subclass of
java.rmi.RemoteException, while
TransactionRolledbackLocalException is a subclass of
javax.ejb.EJBException.
Sample questions
Question 1:
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:
Explanation:
The critical point here is to understand the information contained in the question
statement. First, we know that the bean throws a javax.ejb.EJBException,
so we know we are dealing with a local client. Therefore, we can eliminate
choices C, D, and E right away.
When a business method that executes in the context of the local caller's
transaction throws a javax.ejb.EJBException, the EJB container is
required to throw javax.ejb.TransactionRolledbackLocalException,
as mentioned in Table 15 on page 375 of the EJB 2.0 specification. Therefore,
choice B is correct.
Please refer to sections 18.2.2, 18.3.1, and 18.4.2.1 of the EJB 2.0 specification
for further details (see Resources on page113 ).
Question 2:
In which of the following cases will the EJB container discard a bean instance
when an application exception is thrown from one of the bean's method?
Choices:
Correct choice:
Explanation:
Please refer to section 18 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Summary
This section provided a look at the effects of various exceptions and errors
encountered in EJB applications. We saw that application exceptions represent
error conditions that the client expects and might be able to recover from, while
system exceptions indicate conditions that are unrecoverable. We also explored
the container and bean provider's responsibilities when dealing with different
exceptions. It is important to be aware of the different exception types received
by local and remote clients. Finally, we saw the details of the most common
application and system exceptions in EJB.
Environment entries
The enterprise bean's environment allows the bean behavior to be customized
without the need to access or change the bean's source code. The container
provides an implementation of the JNDI naming context that stores the
enterprise bean environment.
Environment entries are variables whose values are specified in the deployment
descriptor and looked up by the bean using JNDI interfaces. Each enterprise
bean defines its own set of environment entries. These values are read only at
runtime.
The value of an environment entry is of the Java type declared by the Bean
Provider in the deployment descriptor.
<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>
° String
° Character
° Integer
° Boolean
° Double
° Byte
° Short
° Long
° Float
The Deployer must ensure that the values of all the environment entries
declared by the bean are set to meaningful values. The Deployer uses the tools
provided by the container to create the environment entries that are declared in
the enterprise bean's deployment descriptor by the Bean Provider. He may set
different values for the enterprise bean environment entries for each
deployment/home of the bean.
EJB references
An enterprise bean can refer to the homes of other enterprise beans using
"logical" names called EJB references. References to other beans can be local
or remote.
The Bean Provider declares the EJB references in the deployment descriptor
and looks up the home interface of the referenced enterprise bean in the
enterprise bean's environment using JNDI. The Deployer binds the EJB
references to the real JNDI names of the enterprise bean homes in the target
operational environment.
Local EJB references are declared using the <ejb-local-ref> element and
remote EJB references, using the <ejb-ref> element. The EJB specification
recommends -- but does not require -- that all references to other enterprise
beans be organized in the ejb sub-context of the bean's environment (that is, in
the "java:comp/env/ejb" JNDI context).
<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>
...
</entity>
A client can look up the home interface of the referenced bean using the
following code:
<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>
<session>
<ejb-name>EmployeeRecord</ejb-name>
...
</session>
The Deployer:
° Must ensure that all the declared EJB references are bound to the homes of
enterprise beans that exist in the operational environment
° Must ensure that the target enterprise bean is type-compatible with the types
declared for the EJB reference
° Must bind the enterprise bean reference to the home of the enterprise bean
specified as the link's target, if an EJB reference declaration includes the
<ejb-link> element
° javax.jms.QueueConnectionFactory or the
javax.jms.TopicConnectionFactory: For obtaining JMS connections
<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
The following code sample illustrates obtaining a JDBC connection using the
reference declared above:
The Bean Provider must declare all the references to administered objects
associated with resources using the <resource-env-ref> elements of the
deployment descriptor. A resource environment reference is scoped to the
enterprise bean whose declaration contains the <resource-env-ref>
element. The Deployer binds the resource environment references to
administered objects in the target operational environment.
The EJB specification recommends, but does not require, that all resource
environment references be organized in the appropriate subcontext of the
bean's environment for the resource type (for example, in the
<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:
Sample questions
Question 1:
Which of the following are valid Java types that the <env-entry-type>
deployment descriptor element can contain?
Choices:
° A. java.lang.Integer
° B. int
° C. java.lang.Double
° D. double
° E. java.lang.Object
Correct choice:
A and C
Explanation:
The only Java types that are valid values for the <env-entry-type>
deployment descriptor element are:
° java.lang.Byte
° java.lang.Short
° java.lang.Character
° java.lang.Integer
° java.lang.Long
° java.lang.Float
° java.lang.Double
° java.lang.Boolean
° java.lang.String
Choice B and D are incorrect because you cannot specify a primitive type as
the type for an environment entry value.
Please refer to section 20.2.1.2 of the EJB 2.0 specification for further details
(see Resources on page113 ).
Question 2:
Choices:
° A. <ejb-ref-name>
° B. <ejb-ref-type>
° C. <home>
° D. <ejb-link>
° E. <remote>
Correct choice:
Explanation:
° <ejb-ref-name>
° <ejb-ref-type>
° <remote>
° <home>
The <ejb-ref-name> element specifies the EJB reference name; its value is
used in the enterprise bean code. The <ejb-ref-type> element specifies the
expected type of the enterprise bean -- session or entity. The <home> and
<remote> elements specify the expected Java types of the referenced bean's
home and component interfaces.
For more information, refer to section 20.3.1.2 of the EJB 2.0 specification (see
Resources on page113 ).
Summary
One of the most special features of enterprise beans is the support for
customizing the bean at deployment time without modifying the source code in
any way. In the bean's unique environment, we learned how to configure
different things like environment entries, resource manager connection
factories, enterprise bean references, and resource environment references.
Using these declared references, the Bean Provider looks up the different
variables or objects using JNDI interfaces.
Overview
Security management in EJB applications can be achieved in two ways:
programmatically and declaratively. It is preferable to choose the declarative
way because you can customize the security policies through the deployment
descriptor without altering the source code of the bean. However, when
instance-level authorization is required, you need to make use of programmatic
security.
A security role is a logical role that a given type of user must belong to in order
to successfully use an application. Security roles are mapped to real world
users and groups when the bean is deployed. Because you don't have to hard
code specific user identities into the bean code, it makes enterprise beans more
portable. You need to use security roles whether you are using declarative or
programmatic authorization.
Programmatic security
To gain fine-grained control over security, which cannot be achieved through
declarative authorization, you can use programmatic access control. To do so,
we need to get the identity of the users who are invoking the bean methods.
<entity>
<ejb-name>PayrollEJB</ejb-name>
<ejb-class>com.abc.PayrollBean</ejb-class>
<security-role-ref>
<role-name>payroll</role-name>
</security-role-ref>
</entity>
A security role reference is scoped to the session or entity bean element whose
declaration contains the <security-role-ref> element.
<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,
as illustrated below:
<assembly-descriptor>
<security-role>
<role-name>payroll-department</role-name>
</security-role>
</assembly-descriptor>
Declarative security
The Application Assembler can restrict the access to bean methods to certain
privileged roles by defining method permissions in the deployment descriptor. A
method permission is a permission to invoke the specified method of the
enterprise bean's home and component interfaces.
<method-permission>
<role-name>payroll-department</role-name>
<method>
<ejb-name>PayrollEJB</ejb-name>
<method-name>findByPrimaryKey</method-name>
</method>
</method-permission>
<method-permission>
<role-name>payroll-department</role-name>
<method>
<ejb-name>PayrollBean</ejb-name>
<method-intf>Local</method-intf>
<method-name>myMethod</method-name>
<method-params>
<method-param>String</method-param>
<method-params>
</method>
</method-permission>
The run-as identity is designated by one of the security roles defined by the
application assembler in the deployment descriptor, as shown in the following
example:
<session>
<ejb-name>EmployeeInfo</ejb-name>
<security-identity>
<run-as>
<role-name>admin</role-name>
</run-as>
</security-identity>
</session>
The run-as identity establishes the identity the enterprise bean will use when it
makes calls to other enterprise beans; it does not affect the identities of its
callers.
The Deployer must ensure that the assembled application is secure after it has
been deployed in the target operational environment. He also performs any
tasks that have been left unfinished by the Application Assembler.
Sample questions
Question 1:
Choices:
Correct choice:
A and D
Explanation:
Choice A is correct because the run-as identity always applies to the enterprise
bean as a whole.
Choice D is correct because the run-as identity establishes the identity the
enterprise bean will use when it makes calls.
Please refer to section 21.3.4 of the EJB 2.0 specification for further details (see
Resources on page113 ).
Question 2:
Read the following code (assume that all references have been properly
initialized):
Choices:
° A. <security>
° B. <security-role>
° C. <security-role-ref>
° D. <security-role-reference>
° E. None of the above
Correct choice:
Explanation:
If some code can only be accessed based on the caller's role, the Bean
Provider declares the role used in the code by utilizing the
<security-role-ref> deployment descriptor element. Therefore, choice C
is correct, while choice E is incorrect.
Note that another way to achieve the same result would be to assign the admin
security role to the getAdminPassword() method in a
<method-permission> element.
Please refer to section 21.2.5.3 of the EJB 2.0 specification for further details
(see Resources on page113 ).
Summary
In this section, you learned about programmatic and declarative security
management techniques. Different processes are involved, such as defining
security roles, security role references, and method permissions, which are
handled by the various EJB roles like Bean Provider, Application Assembler,
and Deployer.
We also discussed the two programmatic security control methods that are
invoked on the context of the enterprise bean.
We hope that this tutorial has been effective in providing you a clear insight into
the exam objectives and preparing you for the certification.
Resources
° Download the EJB 2.0 Specifications
(http://java.sun.com/products/ejb/docs.html#specs) .
2001)
° Mastering Enterprise JavaBeans -- 2nd Edition by Ed Roman, Scott
Ambler, Tyler Jewell, and Floyd Marinescu (Wiley 2001)
° An introductory article on SCBCD certification by the authors of this
tutorial.
° Practice and assess your knowledge level using the Whizlabs SCBCD Exam
Simulator (http://www.whizlabs.com/products/scbcd/scbcd.html) .
° Get effective guidance and reinforce your concepts for the exam by enrolling
in Whizlabs SCBCD Instructor-Led Online Training
(http://www.whizlabs.com/scbcd/training.html) .
Your feedback
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial
generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT
extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG
heading graphics, and two PDF files. Our ability to generate multiple text and binary formats
from a single source file illustrates the power and flexibility of XML. (It also saves our
production team a great deal of time and effort.)