Escolar Documentos
Profissional Documentos
Cultura Documentos
EJB Points
3. Callback methods are those methods, which are called by the container when a event is
about to occur or has just occurred. This notifies the bean instance about the change in
the environment.
5. RMI uses the protocol, JRMP but EJB uses RMI-IIOP protocol
7. In entity beans, ejbActivate () is called when the bean instance is swapped into the
EJBObject and ejbPassivate() is called when bean instance is swapped out of the
EJBObject.
8. Entity beans support concurrency but session beans never support concurrency.
10. when a entity bean instance is about to be destroyed or deallocated for garbage collection,
unsetSessionContext() method is called by the container. In session bean ejbRemove () is
called.
11. In stateless session bean, ejbCreate() should have no arguments, and this method
is called when the bean instance move from does not exist state to the pooled state.
Please note that ejbCreate() is called prior of client calling the create() method of the
home interface, unlike entity and stateful session beans.
13. HomeHandle and Handle are interfaces which allows the the Home and Remote interfaces
to be serialized.
14. Entity beans cannot handle its own transactions, the bean developed needs to specify the
type of transaction he wants in the Deployment descriptor. i.e, he cannot use any
transaction methods defined in javax.transaction.UserTransaction interface provided by
getUserTransaction() method in EJBContext interface.
15. Session beans can handle its own transactions. By specifying <transaction-
type>Bean</transaction-type> in the Deployment Descriptor.
16. when the bean uses its own transactions, setRollbackOnly() and getRollbackOnly()
methods of EJBContext Interface can never be called. If called RemoteException will be
thrown.
Mohan
EJB FAQ Page 2 of 36
17. 2-PC, Two Phase Commit is a concept which support distributed transactions, i.e a single
transaction can be carried on over 2 or more servers.
19. When a system exception is thrown, a transaction is rolled back. RuntimeException and its
subclasses like NullPointerException and ClassCastException are System Exceptions.
EJBException is also a subclass of runtime exception.
20. Application Exception , like user defined exception and exceptions defined by ejb
specification, like FinderException, CreateException never results in the rolling back of a
transaction.
21. Sub system exceptions like jdbc exceptions (SQLException) and JNDI exceptions
(NamingException) too never results in the rolling back of a transaction.
22. When Application Exceptions and Sub systems exceptions are thrown, they will have to be
caught and rethrown as a EJBException (which will result in rolling back of a transaction)
23. EJB specification, preasumes that the user is already authenticated during the JNDI loop
up. It only supports authorization. (This can be configured in the Deployment
Descriptors, by providing method permissions to specific role names)
Mohan
EJB FAQ Page 3 of 36
When was EJB 1.1 defined?
EJB 1.1 is currently in Public Release 2, a non-final preliminary draft. Final release of the specification is
expect by the end of the 4th quarter.
• Java RMI-IIOP argument and reference types must be supported, but any
protocol can still be used including IIOP, JRMP, HTTP, or a proprietary protocol.
In other words, the client API must support the Java RMI-IIOP programming
model for portability, but the underlying protocol can be anything.
• Declarative isolation levels are no longer available. Isolation levels are now
managed explicitly through JDBC (BMP), the database or other vendor specific
mechanisms.
• The basic EJB roles have been expanded and redefined to better separate
responsibilities involved in the development, deployment, and hosting of
enterprise beans.
In Plain English:
Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object
system similar to CORBA and Microsoft Transaction Server, but based on the Java
platform. EJB specifies how developers should build components that can be accessed
remotely and how EJB vendors should support those components. EJB components,
called enterprise beans, automatically handle transactions, persistence, and
authorization security, so that the developer can focus on the business logic.
Mohan
EJB FAQ Page 4 of 36
What is an enterprise bean?
An enterprise bean is a server-side component -- defined in the Java technology -- which adheres to the
Enterprise JavaBeans server-side component model. A server-side component is business object that can
be accessed remotely. Many server-side component models exist: CORBA specifies CORBA objects;
Microsoft Transaction Server (MTS) defines COM/DCOM; and EJB specifies enterprise beans.
Enterprise beans can be developed to represent business concepts like Employee, Order,
TravelAgent, etc. Enterprise beans can be assembled into applications that solve
enterprise business problems.
EJB has two basic types of enterprise beans: Session and Entity. Depending on the type
of enterprise bean used, features like persistence, transactions, security, and multiple
concurrent access can be managed automatically.
Enterprise JavaBeans has been adopted by most distributed object vendors and is
considered a standard for developing distributed object systems in Java. All EJB vendors
must implement the same EJB specification which guarantees a consistent programming
model across servers. In addition, because EJB is widely supported by many vendors,
corporations do not have to worry about vendor lock-in; enterprise beans will run in any
EJB compliant server.
Session beans can act as agents modeling workflow or provide access to special
transient business services. As an agent, a stateful session bean might represent a
customer's session at an online shopping site. As a transitive service, a stateless session
bean might provide access to validate and process credit card orders.
Session beans do not normally represent persistent business concepts like Employee or
Order. This is the domain of a different component type called an entity bean.
The stateful session bean is EJB component that implements the javax.ejb.SessionBean
interface and is deployed with the declarative attribute "stateful". Stateful session beans
are called "stateful" because they maintain a conversational state with the client. In
other words, they have state or instance fields that can be initialized and changed by the
client with each method invocation. The bean can use the conversational state as it
process business methods invoked by the client.
Stateful session beans are usually developed to act as agents for the client, managing
the interaction of other beans and performing work on behalf of the client application.
An example is a shopping cart stateful session bean that tracks a client's product choices
and can execute a sale when requested. Below is partial example of a stateful session
bean that is used as a shopping cart.
//get reference to the CreditService bean and process the customers charge
CreditService cardSwipper = ... get credit card service bean
Charge charge = cardSwipper.charge(CreditCard, total);
// get reference to the OrderHome and create a new shipping order bean (record)
OrderHome orderHome = ... get the Order beans Home object
Order order = orderHome.create(customer, products, charge);
}
...
}
In the example above the ShoppingCartBean keeps track of the Customer and the items
chosen by the client application. This is the bean's conversational state. Once the client
application is ready to execute a sale, the ShoppingCartBean manages the interactions
of the Customer, Product, CreditServer, and Order beans in a workflow that results in a
charge against the customers credit card and the creation of a shipping order. The
ShoppingCartBean behaves as an agent for the client managing the interaction of these
other beans, tracking chosen items, and executing the sale. The below table identifies
the beans types used in the ShoppingCartBean example above.
Bean Name Bean Type
ShoppingCartBean Stateful Session
CreditService Stateless Session
Customer Entity
Product Entity
Order Entity
From the clients perspective only the Customer and ShoppingCart beans are visible,
because the client application works with the bean's remote interface while the bean
itself resides on the server. This means that the client need only be concerned with the
business methods made public by the ShoppingCartBean. Below is an example of the
client applications view of the ShoppingCartBean. (Note: The client interacts with the
beans remote interface not the bean itself. The remote interface is called the
ShoppingCart.)
// somewhere in the client application (applet, servlet, etc.)
// obtain the home objects (factories) for the Customer and ShoppingCart beans
CustomerHome custHm = ... get CustomerHome
ShoppingCartHome shpCrtHm = ... get ShoppingCartHome
// create a new ShoppingCart initialized with the Bob Johnsten Customer bean
ShoppingCart shoppingCart = shpCrtHm.create (customer);
Mohan
EJB FAQ Page 6 of 36
...
Product product = ... get reference to bean representing the product chosen
// add product to customer's shopping cart
shoppingCart.addItem(product);
...
//charge customer for products and create a shipping order
shoppingCart.executeSale( );
Session beans like the shoppingCartBean only live as long as the client maintains a
connection. In other words, they represent some aspect of the client's current session
with the system and die when the client ends that session. Session beans are generally
not fault tolerant. A system failure or shut down will result in the death of session bean
and a loss of any conversation state it maintained prior to the failure. (This is a
conceptual lifecycle of a session bean. Some vendors can make them more fault tolerant
and longer lasting).
Stateless session beans are usually developed as a set of related and simple services.
Think of a session bean as a functional API where each business method represents an
isolated independent service. An example is a CreditService bean that provides methods
for making charges against different types of credit cards (MC, Visa, Discovery, etc).
Entity beans have identity, where each bean represents a unique set of data. An entity
bean of type Customer, for example, would have thousands of identities -- one for each
customer in the database. Entity beans can be safely shared by many clients, so that
several applications can access the same bean identity at the concurrently.
A bean developer might choose to create a Customer bean to represent customer data
in the database. The bean developer decides what data from the database represents a
customer and how customers are uniquely identified. The bean developer also decides
what business methods the Customer bean expose and what data can be changed or
read. Below is the server-side component definition of a Customer bean.
// business methods
public PersonName getName( )
{ return new PersonName(firstName, lastName);
}
public void setName(PersonName name)
{ lastName = name.getLastName();
fistName = name.getFirstName();
}
public Date lastActive( )
{ return lastActive;
}
...
}
Note: Only a subset of the bean code normally implemented is
shown here for brevity. Ordinarily the bean would also
implement special EJB specific callback methods that are not
important to this FAQ entry.
The ejbCreate ( ) method is used only once in the life type of a bean identity when its
first created. In this case we initialize the bean with the customer's id number and
name. The lastActive value is set within the method. The ejbCreate ( ) creates and
returns the customer bean's identity, which is called a primary key in EJB. A primary key
is a object that represents a unique identifier for a bean. In the case of the Customer
bean the primary key is the CustomerKey which is an object that wrappers the
customer's id. Primary keys can be as simple as a String value or more be more
Mohan
EJB FAQ Page 8 of 36
complicated like a key that wraps several values that together represent a unique index
to the bean identity. Below is the definition of the CustomerKey object.
In addition to the business methods and the ejbCreate( ) methods there are a number of
notification methods that the bean container (EJB server) uses to alert that bean that
some significant event in its lifecycle is about to, or just has, occurred. Of particular
importance are the two notification methods (ejbLoad( ) and ejbStore( )) used to alert
the bean when its being synchronized with the database. The behavior of these methods
changes depending on whether the bean is designed for BMP or CMP. This is investigated
in more detail under the FAQ entries Java:API:EJB:EntityBean:BMP and
Java:API:EJB:EntityBean:CMP.
A CMP bean is an entity bean whose state is synchronized with the database
automatically. In other words, the bean developer doesn't need to write any explicit
database calls into the bean code; the container will automatically synchronize the
persistent fields with the database as dictated by the deployer at deployment time.
When a CMP bean is deployed, the deployer uses the EJB tools provided by the vendor
to map the persistent fields in the bean to the database. The persistence fields will be a
subset of the instance fields, called container-managed fields, as identified by the bean
developer in the deployment descriptor.
In the case of a relational database, for example, each persistent field will be associated
with a column in a table. A bean may map all its fields to one table or, in the case of
more sophisticated EJB servers, to several tables. CMP are not limited to relational
database. CMP beans can be mapped to object databases, files, and other data stores
including legacy systems.
With CMP, the bean developer doesn't need to write any database access logic into the
bean, but bean is notified by the container when its state is synchronized with the
database. The container notifies the bean using the ejbLoad( ) and ejbStore( ) methods.
The ejbLoad( ) method alerts the bean that its container-managed fields have just been
populated with data from the database. This gives the bean an opportunity to do any
post processing before the data can be used by the business methods. The ejbStore( )
method alerts the bean that its data is about to be written to the database. This give the
bean an opportunity to do any pre-processing to the fields before they are written to the
Mohan
EJB FAQ Page 9 of 36
database. The below bean code demonstrates how these method might be employed on
a Customer CMP entity bean.
// business methods
public PersonName getName( )
{ return name;
}
public void setName(PersonName name)
{ name = name;
}
// called just after container-managed fields are updated from database
public void ejbLoad( )
{ name = PersonName(firstName, lastName);
}
// called just before container-managed fields are written to database
public void ejbStore( )
{ lastName = name.getLastName( );
firstName = name.getFirstName( );
}
...
}
In the case of the Customer bean the ejbLoad( ) and ejbStore( ) are used to wrapper
the name fields (lastName and firstName) in a PersonName object which is more user
friendly for the bean client. The ejbLoad( ) method wrappers the fields so that the
getName( ) method access an up-to-date copy of the name data. The ejbStore( )
method unwraps the name data and places them back into the container-managed fields
so that the database is updated with the most recent changes.
The ejbLoad( ) and ejbStore( ) methods are typically called just before a transaction
begins and when a transaction is about to commit. This ensures that the container-
managed fields are synchronized with the database when the bean is in use. Some EJB
servers will optimize the container so that data is not written to the database unless its
dirty; that container-managed fields have been changed.
CMP is the most difficult EJB feature for vendors to support. It requires very
sophisticated tools for mapping bean fields to a data source and generating the
underlying stubs and skeletons to support this mapping. CMP, however, provide a
unique opporutnity for organizations developing distributed object systems. With CMP, a
shrink-wrapped bean ( a bean developed by a third party) can be deployed and mapped
into an organization's existing database. Obviously, this is an idyllic scenario, but not
unreasonable. CMP entity beans exemplify the spirit of component technology; the reuse
of components across projects, organizations, and industries.
Note: CMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the
Bean-Managed Persistence (BMP) beans. See Java:API:EJB:EntityBean:BMP for details on
how BMP beans use these methods.
What is a BMP bean?
BMP: Bean-Managed Persistence
A BMP bean is an entity bean that synchronizes its state with the database manually. In
other words, the bean developer must code explicit database calls into the bean itself.
BMP provides the bean developer with more flexibility in the how the bean reads and
writes its data than a container-managed persistence (CMP) bean. CMP bean is limited
to the mapping facilities provided by the EJB vendor, BMP beans are only limited by skill
of the bean developer.
The ability to code an entity bean's persistence logic explicitly is important when the EJB
container's CMP features are insufficient to meet the needs of the entity bean. Entity
Mohan
EJB FAQ Page 10 of 36
beans that need to synchronize their state with several data sources are excellent
candidates for BMP. So are beans that need to access to data sources (possibly legacy
systems) that are not supported by CMP. In addition, BMP bean are often employed
when a vendors CMP facilities are not sophisticated enough to handle complex Object-
to-Relational mapping.
The BMP bean manages its own persistence, but relies on the container to coordinate its
reads and writes so that persistence is accomplished in a transactional safe manner.
Coordination with the container is accomplished through two mechanisms: The
persistence callback methods (ejbLoad( ) and ejbStore( )); and the Environment Naming
Context (EJB).
The ejbLoad( ) and ejbStore( ) methods notify a bean that its time to read and write
data to the database respectively. In a BMP entity bean the code for reading and writing
data to the database is done within these methods. The ejbLoad( ) is called at the
beginning of a transaction, just before any business methods are executed, and the
ejbStore( ) is called at the end of a transaction just before its committed. This keeps the
bean state in perfect synchronization with transactions being executed, without the bean
developer having to explicitly manage the transactional operations.
When JDBC is used to for persistence, the Environment Naming Context (ENC) is a JNDI
namespace that provides the bean with access to database connections (among other
things). The database connections obtained from the JNDI ENC are managed by the
container, so that they are automatically enrolled in transactions and pooled. (The
extent to which this is supported depends largely on the EJB vendor.) The container may
also manage other data source APIs, but JDBC is standard.
Below is an example of an entity bean, the Customer bean that is designed to use BMP
to synchronize its own state with a CUSTOMER table in the database.
// business methods
public PersonName getName( )
{ return new PersonName(firstName, lastName);
}
public void setName(PersonName name)
{ firstName = name.getFirstName( );
lastName = name.getLastName( );
}
// called just before a business method can be invoked at the beginning of a
transaction
public void ejbLoad( )
{
try
{
javax.sql.DataSource ds =
(DataSource)jndiContext.lookup("java:comp/env/jdbc/Database");
java.sql.Connection con = ds.getConneciton( );
PreparedStatement ps =
con.prepareStatement("select lastname, firstname from CUSTOMER
where id = ?");
CustomerKey key = (CustomerKey)ejbContext.getPrimaryKey( );
customerNumber = key.id;
ps.setLong(1, customerNumber);
java.sql.ResultSet result = ps.executeQuery( );
while(result.next())
{
lastName = result.getString(" lastname");
firstName= result.getString(" firstname");
Mohan
EJB FAQ Page 11 of 36
}
con.close();
}catch(Exception e)
{ throw new EJBException(e);
}
}
}
catch(Exception e){throw new EJBException(e);
}
}
...
}
Note: BMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the
Container-Managed Persistence (CMP) beans. See Java:API:EJB:EntityBean:CMP for details on
how CMP beans use these methods.
JavaBeans
The original JavaBeans specification is based on the java.beans package which is a
standard package in the JDK. Components built on the JavaBeans specification are
intraprocess components that live in one address space and are typically used for
Graphical User Interface (GUI) as visual widgets like buttons, tables, HTML viewers, etc.
Enterprise JavaBeans
The EJB specification is based on the javax.ejb package, which is a standard extension
package. Components built on the EJB specification are interprocess components that
live in multiple address spaces as distributed object. These components are used as
transactional business objects that are accessed as remote objects.
Passivation and activation are two phases of a resource management technique that
reduces the number of bean instances needed to service all clients. Passivation is the
process of disassociating a bean instance from its EJB object so that the instance can be
reused or evicted to conserve memory. Activation is the process of associating a bean
instance with an EJB object so that it can service a request. Beans are passivated when
there is a lull in their use and activated when the EJB object receives a client request.
Mohan
EJB FAQ Page 12 of 36
The mechanisms employed in passivation and activation change depending on the bean
type. Stateful beans are usually evicted, while entity beans and stateless beans are
pooled. A more detailed account of how different bean types passivated and activated is
found under the FAQs for that type.
When a stateful bean experiences a lull in use -- between client invocations and
transactions -- the container may choose to passivate the stateful bean instance. To
conserve resources the bean instance is evicted from memory (dereferenced and
garbage collected). When the EJB object receives a new client request, a new stateful
instance is instantiated and associate with the EJB object to handle the request.
Stateful beans maintain a conversational state, which must be preserved before the
bean instance is evicted from memory. To accomplish this, the container will write the
conversational state of the bean instance to a secondary storage (usually disk). Only the
non-transient serializable instance fields are preserved. When the bean is activated the
new instance is populated with the preserved state. References to live resources like the
EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow
-- usually in memory -- by the container.
The javax.ejb.SessionBean interface provides two callback methods that notify the bean
instance it is about to passivated or was just activated. The ejbPassivate( ) method
notifies the bean instance that it is about have its conversational state written to disk
and be evicted from memory. Within this method the bean developer can perform
operations just prior to passivation like closing open resources. The ejbActivate( )
method is executed just after a new bean instance has been instantiated and populated
with conversational state from disk. The bean developer can use the ejbActivate( )
method to perform operations just prior to servicing client request, like opening
resources.
JMS clients can bundle several messages in a transaction simply by using a transactional
session--a UserTransaction object is not required. To create a transactional session, use
either QueueConnection.createQueueSession() or TopicConnection.createTopicSession()
with true as the first argument. (Some JMS implementations support JTA, so that it's
also possible to obtain a UserTransaction object from the JMS server.)
In other environments, for example, a web server that supports servlets and/or
JavaServer Pages (JSP), a JMS server, and others, you obtain a UserTransaction object
via JNDI. Of course, for a servlet to obtain a UserTransaction object, there must be a
JTS-capable server to deliver the object.
Typically, the server provides the JNDI look-up name either directly or via a system or
server property. For example, with the WebLogic server, you would use a code segment
similar to the following:
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("javax.jts.UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
Mohan
EJB FAQ Page 13 of 36
...
With J2EE implementations, you obtain the UserTransaction object with a code segment
similar to the following:
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("java:comp/UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...
If the environment provides the UserTransaction object via a system property, you
would use a code segment similar to the following:
...
String transName = System.getProperty ("jta.UserTransaction");
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup(transName);
ut.begin();
// perform multiple operations...
ut.commit()
...
JNDI remote look-up names and property names vary, of course, across
servers/environment.
Keep in mind that even if the JTS implementation supports nested transactions, this
transaction manager-level support does not guarantee support for nested transactions in
an application. For example, the EJB 1.1 specification does not support nested
transactions.
In the previous scenario, however, the client application developer should address the
question of whether or not it would be better to encapsulate these operations in yet
another session bean, and allow the session bean to handle the transactions via the EJB
container. In general, lightweight clients are easier to maintain than heavyweight
clients. Also, EJB environments are ideally suited for transaction management.
How does a session bean that uses container-managed transactions obtain a JTA
UserTransaction object?
It doesn't! By definition, container-managed transaction processing implies that the EJB container is
responsible for transaction processing. The session bean has only limited control of transaction handling
via the transaction attribute.
How do you configure the transaction characteristics for a session bean with container-
managed transactions?
You must set trans-attribute in the deployment descriptor.
Is it necessary for an entity bean to protect itself against concurrent access from multiple
transactions?
No. One of the motivations for using a distributed component architecture such as Enterprise JavaBeans is
to free the business logic programmer from the burdens that arise in multiprogramming scenarios.
How do beans manage resource connections to back-end services other than databases ?
While EJB 1.1 provides the JNDI ENC for managing standard resources like URL, JDBC, JavaMail and JMS,
connections to other types of resources are not addressed by EJB 1.0 or EJB 1.1, but there are solutions.
Below is a list of some strategies that can provide access to "back-ends" besides relational databases.
This strategy works in stateless session beans and entity beans in EJB servers that pool
and reuse these bean types. In stateless beans you can simply reference the resources
using the instance fields -- stateless beans are not passivated in EJB. In entity beans
you can also reference the connections using instance fields but the field used must not
be declared as a container-managed field in the deployment descriptor.
In both stateless and entity beans there are methods can be used safely to open and
close resource connections at the beginning and end of the beans life.
In stateful session beans the references will need to be released and re-constituted
when the bean is activated using some kind of naming facility native to the reference
type.
Mohan
EJB FAQ Page 15 of 36
With stateless and entity beans the above strategy, Leveraging the instance fields works
well with this strategy.
JNDI references:
It may be possible to access a JNDI service directly from the bean and to attach live
resources to the JNDI service. This depends on the JNDI service provider and your EJB
vendor.
<%
//instantiate the session bean
Account acct = accHome.create ();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
What are all the different kinds of servers?
The servers involved in handling and processing a user's request break down into a few basic types, each
Mohan
EJB FAQ Page 16 of 36
of which may have one or more tasks it solves. This flexibility gives developers a great deal of power over
how applications will be created and deployed, but also leads to confusion over what server is able to, or
should, perform a specific task.
Starting at the basic level, a user is typically submitting a request to a system through a
web browser. (We are conveniently ignoring all other types of clients (RMI, CORBA,
COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The web request
must be received by a Web Server (otherwise known as an HTTP Server) of some
sort. This web server must handle standard HTTP requests and responses, typically
returning HTML to the calling user. Code that executes within the server environment
may be CGI driven, Servlets, ASP, or some other server-side programming language,
but the end result is that the web server will pass back HTML to the user.
The web server may need to execute an application in response to the users request. It
may be generating a list of news items, or handling a form submission to a guest book.
If the server application is written as a Java Servlet, it will need a place to execute, and
this place is typically called a Servlet Engine . Depending on the web server, this engine
may be internal, external, or a completely different product. This engine is continually
running, unlike a traditional CGI environment where a CGI script is started upon each
request to the server. This persistance gives a servlet connection and thread pooling, as
well as an easy way to maintain state between each HTTP request. JSP pages are
usually tied in with the servlet engine, and would execute within the same
space/application as the servlets.
There are many products that handle the web serving and the servlet engine in different
manners. Netscape/iPlanet Enterprise Server builds the servlet engine directly into the
web server and runs within the same process space. Apache requires that a servlet
engine run in an external process, and will communicate to the engine via TCP/IP
sockets. Other servers, such as MS IIS don't officially support servlets, and require add-
on products to add that capability.
When you move on to Enterprise JavaBeans (and other J2EE components like JMS and
CORBA) you move into the application server space. An Application Server is any
server that supplies additional functionality related to enterprise computing -- for
instance, load balancing, database access classes, transaction processing, messaging,
and so on.
EJB Application Servers provide an EJB container, which is the environment that
beans will execute in, and this container will manage transactions, thread pools, and
other issues as necessary. These application servers are usually stand-alone products,
and developers would tie their servlets/JSP pages to the EJB components via remote
object access APIs. Depending on the application server, programmers may use CORBA
or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and
create EJB references as necessary.
Now, one thing that confuses the issue is that many application server providers include
some or all of these components in their product. If you look at WebLogic
(http://www.beasys.com/) you will find that WebLogic contains a web server, servlet
engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a product
like this could be used to handle all aspects of site development. In practice, you would
most likely use this type of product to manage/serve EJB instances, while dedicated web
servers handle the specific HTTP requests.
The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some things
that enterprise beans cannot do. In particular:
Mohan
EJB FAQ Page 17 of 36
Using the java.io package from within a bean is prohibited. The EJB 1.1 Specification,
section 18.1.2 (Programming Restrictions) states the following:
An enterprise bean must not use the java.io package to attempt to
access files and directories in the file system.
The file system APIs are not well-suited for business components to
access data. Business components should use a resource manager
API, such as JDBC API, to store data.
Alternative Solutions
To perform logging operations you must you a resource connection supported by the EJB
programming model. EJB servers may support several resource connection options,
which can be used to log events as shown below:
• JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the log events
as messages.
What is a container?
Enterprise beans are software components that run in a special environment called an EJB container. The
container hosts and manages an enterprise bean in the same manner that a Java WebServer hosts a
Servlet or an HTML browser hosts a Java applet. An enterprise bean cannot function outside of an EJB
container. The EJB container manages every aspect of an enterprise bean at run time including remote
access to the bean, security, persistence, transactions, concurrency, and access to and pooling of
resources.
The container isolates the enterprise bean from direct access by client applications.
When a client application invokes a remote method on an enterprise bean, the container
first intercepts the invocation to ensure persistence, transactions, and security are
applied properly to every operation a client performs on the bean. The container
manages security, transactions, and persistence automatically for the bean, so the bean
developer doesn't have to write this type of logic into the bean code itself. The
enterprise bean can focus on encapsulating business rules, while the container takes
care of everything else.
Mohan
EJB FAQ Page 18 of 36
Containers will manage many beans simultaneously in the same fashion that a Java
WebServer manages many Servlets. To reduce memory consumption and processing,
containers pool resources and manage the lifecycles of all the beans very carefully.
When a bean is not being used a container will place it in a pool to be reused by another
client, or possibly evict it from memory and only bring it back when its needed. Because
client applications don't have direct access to the beans -- the container lies between the
client and bean -- the client application is completely unaware of the containers resource
management activities. A bean that is not in use, for example, might be evicted from
memory on the server, while its remote reference on the client remains intact. When the
client invokes a method on the remote reference, the container simply re-incarnates the
bean to service the request. The client application is unaware of the entire process.
JNDI: Java Naming and Directory Interface is a Java extension API for
accessing naming systems like LDAP, NetWare, file systems, etc. Every
bean automatically has access to a special naming system called the
Environment Naming Context (ENC). The ENC is managed by the
container and accessed by beans using JNDI. The JNDI ENC allows a
Mohan
EJB FAQ Page 19 of 36
bean to access resources like JDBC connections, other enterprise
beans, and properties specific to that bean.
The EJB specification defines a bean-container contract, which includes the mechanisms
(callbacks, EJBContext, JNDI ENC) described above as well as a strict set of rules that
describe how enterprise beans and their containers will behave at runtime, how security
access is checked, transactions are managed, persistence is applied, etc. The bean-
container contract is designed to make enterprise beans portable between EJB
containers so that enterprise beans can be developed once then run in any EJB
container. Vendors like BEA, IBM, and Gemstone sell application servers that include EJB
containers. Ideally, any enterprise bean that conforms to the specification should be able
to run in any conformant EJB container.
Portability is central to the value that EJB brings to the table. Portability ensures that a
bean developed for one container can be migrated to another if another brand offers
more performance, features, or savings. Portability also means that the bean
developer's skills can be leveraged across several EJB container brands, providing
organizations and developers with better opportunities.
In addition to portability, the simplicity of the EJB programming model makes EJB
valuable. Because the container takes care of managing complex tasks like security,
transactions, persistence, concurrency and resource management the bean developer is
free to focus attention on business rules and a very simple programming model. A
simple programming model means that beans can be developed faster without requiring
a Ph.D. in distributed objects, transactions and other enterprise systems. EJB brings
transaction processing and distributed objects development into the mainstream.
How do I introspect a bean at run time to discover its type(s) and available methods?
Client applications or beans can access meta data about a bean from its EJBMetaData object. The
EJBMetaData object is obtained from the bean's EJB home reference using the EJBHome.getEJBMetaData(
) method as shown below:
AccountHome acctHome = ... get a reference to the bean's EJB home.
EJBMetaData ejbMetaData = acctHome.getEJBMetaData ( );
The EJBMetaData object implements the javax.ejb.EJBMetaData interface which defines
methods for obtaining the class of the bean's remote interface, home interface, bean
type (entity, stateful or stateless session), and the primary keys type (entity only). A
reference to the bean's EJB home can also be obtained. Below is the interface definition
of EJBMetaData.
package javax.ejb;
}
Mohan
EJB FAQ Page 20 of 36
There are no mechanisms a client can use to introspect on a the bean class itself. This
makes sense since a bean, as a component, is represented by its remote and home
interfaces. The bean class itself should not be visible to the client.
The EJBMetaData is designed to be used by IDEs and other builder tools that may need
generic methods for obtaining information about a bean at runtime.
While deploying CMP entity beans, which fields in the bean are container-managed and how are
they identified?
Container-managed fields may be specified in the bean's deployment descriptor. An entity bean, for
example, has an XML deployment descriptor containing elements similar to the following:
<enterprise-beans>
<entity>
<description>This entity bean models an audio compact disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>
In the above deployment descriptor, the container-managed fields are specified to be
upc, title, artist, type, and price.
Mohan
EJB FAQ Page 21 of 36
While the deployment descriptor provides information about the container-managed
fields for use during deployment, the details of how these fields are mapped into the
database (or other persistent storage mechanism) are controlled by the container-
specific deployment process itself. To learn more about the container-specific
deployment process, you will need to consult your container vendor's documentation.
What newsgroups and mailing lists are available to learn more about EJBs?
Sun manages two EJB-related mailing list:
The J2EE-INTEREST mailing list is for discussion of Sun's Java 2 Enterprise Edition
platform and for users of Sun's J2EE Reference Implementation. A searchable archive of
this list can be found at http://archives.java.sun.com/archives/j2ee-interest.html.
You may subscribe or unsubscribe to either of these lists by following the links on the
above archive pages.
Its possible that authentication security, which validates the identities of users accessing
the system, will be defined in EJB 2.0. Its likely that the Java Authentication and
Authorization security service will be used, but this is not definite. If this authentication
is added to EJB, it will provide a standard and portable model for authenticating (login)
of users.
Secure communication, which is commonly implemented with technologies like SSL, may
also be defined in EJB 2.0, but this is less likely since it's more of a value added vendor
feature than a requirement for portability.
The release date for EJB 2.0 (as of this writing) has not been determined. It seems likely
that EJB 2.0 will become final sometime in late 2001 or 2002.
Because an enterprise bean is not one object -- its the composition of several parts --
traditional OO inheritance is not possible. The constituent Java parts (remote, home,
bean class) of an enterprise bean may themselves subtype or serve as super-type, but
the bean as a whole (the sum of its parts) doesn't support inheritance.
The file system APIs are not well-suited for business components to
access data. Business components should use a resource manager
API, such as JDBC API, to store data.
• JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the I/O data
as messages.
With container-managed persistence (CMP) its more difficult because you are dependent
on the versatility of the EJB vendor. In other words, if the vendor does not support
sophisticated find operations or syntax, its more difficult to declare complex find
operations at deployment time. With CMP you have a couple options:
• Convert the CMP bean to a BMP bean and hand code the
ejbFind methods yourself. This is a classic scenario for
using BMP over CMP; when the EJB vendor is not
sophisticated enough to support a bean's data access needs.
NOTE:
A common design error is to implement search operations that filter results of multi-
entity find requests implemented by other entity beans. This should be avoided. If you
can not find the entity beans in one find request, then you should use a search method
in a session bean.
Mohan
EJB FAQ Page 23 of 36
These functions are reserved for the EJB Container. Allowing the
enterprise bean to manage threads would decrease the Container’s
ability to properly manage the runtime environment.
Related FAQs:
• http://www.jguru.com/jguru/faq/view.jsp?EID=15893
Resource Management
Containers manage every aspect of the runtime environment used by enterprise beans
including transactions, access control, life cycle, resource connections, VM security, class
loading, and threads. This allows the container to conserve as many resources as
possible, which is important when there are hundreds of enterprise beans servicing
thousands of clients. Without strict management of resources like memory and threads,
EJB systems might consume to many resources (memory and cycles), which would
result in a slow system, a prospect that is untenable in a high-transaction environment.
Threads started and managed by enterprise beans would not be managed by the
container, which would make it difficult to conserve resources.
Security
There is no way for a container system to know in advance that a bean's use of threads
is benign. While intentions may be sincere it is possible -- probably inevitable -- that
developers would create malignant beans that spawn so many threads that the entire
system slows down. One bean instance's misuse of threads or the commutative effect of
many instances could cause a system slowdown. This is an insurgent denial of service,
where the beans themselves sabotage a system's ability to respond to client requests.
Security is a very good reason for denying bean's the privilege of starting and managing
their own threads.
Thread-Specific Storage
Thread-Specific Storage (TSS) is an established and common technique employed by
vendors to propagate and track client requests through the container system. It involves
associating data with a thread. The data may be information about the client's identity,
the transaction context, and other information, which can be accessed by any part of the
container without having to pass the data explicitly. This is especially useful when
enterprise beans invoke other enterprise beans or access resources, because it provides
a convenient and transparent mechanism for transferring information about the who is
making the request and under what circumstances. Each vendor will use the TSS
technique differently according to the mechanics of their server. Threads started and
managed by the enterprise bean explicitly would not have the proper TSS -- that would
require intimate knowledge and access to the vendors container system. Without the
right TSS the enterprise bean's threads can not operate within the container system
properly. This is another reason why bean are not allowed to start and manage their
own threads, it would short-circuit the vendor's use of TSS.
Related FAQs:
• What is a container?
We will use an example to show how it's done. Say, there are 2 session beans, Tiger and
Lion, that share some method signatures but provide different implementations of the
methods.
Mohan
EJB FAQ Page 24 of 36
• AnimalHome and Animal are the home and remote interfaces.
The signatures of the polymorphic methods are in Animal.
How is an EJB primary key implemented when the database doesn't have a primary key?
A primary key is an object that uniquely identifies the entity bean. According to the specification, the
primary key must be unique for each entity bean within a container. Hence the bean's primary key maps
to the PK in the database (provided its persisted to a database). You may need to create a primary key in
the database for the sake of referential integrity. This does not, however, mean you NEED a primary key
in the database. As long as the bean's primary key (which maps to a column or set of columns) can
uniquely identify the bean it should work.
Mohan
EJB FAQ Page 25 of 36
Is there a J2EE server for RedHat Linux 6.1?
There are couple of EJB servers Check this website
http://www.flashline.com/Components/appservermatrix.jsp?sid=954859879375-3501378072-150
How does Container Managed Persistence work with automatically generated database ID
fields? Should I map the ID field explicitly or leave it unspecified?
In the Deployment Descriptor, map the normal fields appropriately, but don't specify the
auto-id field as one of the container managed fields.
How can one have non-client specific state in stateless session beans?
You can use the Environment to get a pointer to a somewhat global state, that's shared among all EJBs:
public class test implements SessionBean
{
private transient SessionContext ctx;
static final float PIE=3.14 ;
private transient Properties myprops;
}
What happens when two users access an Entity Bean concurrently?
Taken from Enterprise JavaBeans by Richard Monson-Haefel, "EJB, by default, prohibits concurrent access
to bean instances. In other words, several clients can be connected to one EJB object, but only one client
thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the
EJB object, no other client can access that bean instance until the method invocation is complete."
So, to answer your question, two users will never access an Entity Bean concurrently.
If you wish to know more about this issue, I would suggest downloading and reading the
white paper from Sun: http://java.sun.com/products/ejb/docs.html. Some entity beans
may require loopback calls, where bean A is invoked, in turn invoking bean B, which
then invokes a method call on bean A. This kind of concurrency is tricky and is best
avoided.
As a side note, the use of 'synchronized' is not permitted in EJB. (You must leave all that
up to the server.)
What's the reason for having two interfaces -- EJBHome for creating, finding & removing and
EJBObject for implementing business methods. Why not have an single interface which
supports both areas of functionality?
This design reflects the common "Factory" Design pattern. The EJBHome interface is the Factory that
creates EJBObjects. EJBObject instances are the product of the factory. The reason for having two
interfaces is because they are both responsible for different tasks. The EJBHome is responsible for creating
and finding EJBObjects, whilst the EJBObject is responsible for the functionality of the EJB.
Ejb 1.1 spec section 9.4.1 - "The fields must be defined in the entity bean class as
public, and must not be defined as transient."
Mohan
EJB FAQ Page 26 of 36
If your client is a Java client, your client requires some sort of object that will "listen" for
call-backs. This could be either a CORBA or RMI object. Again, you could pass references
to these objects to the EJB, which could then invoke methods on the references.
How do you model for a JOIN operation in a relational database using entity bean(s)? Do you
have to have separate entity beans for each table in the database?
This depends on the granularity and the design of your Entity beans.
A way to do it is to model an Entity for each table and for the join specify a reference to
Entity Bean 2 (from table2 ) from Entity Bean 1 (from table 1). If this is a one-to-one
relationship then you could easily place these into the same Entity bean - this is a design
issue and has other factors involved.
For a one-to-many relationship you could specify a collection of EJB references to Entity
Bean 1 inside Entity Bean 2.
If you're using CMP, the above information will be very much reliant on the EJB CMP tool
that you are using. Each tool has its strengths. I am basing this response on the Inprise
Application Server 4.0.
• How do I connect to SQL Server 6.5 from J2EE for Windows? What
changes should I have to do in the properties file? Can I use the JDBC-
ODBC bridge?
If you insist on initially using a database other than Cloudscape, you should
Mohan
EJB FAQ Page 27 of 36
carefully read and follow the instructions in the following J2EE RI
documentation:
There are two ways for transitioning an entity bean from the ready to the pooled state,
by using the ejbPassivate() or ejbRemove() method. The container uses ejbPassivate ()
to disassociate the bean instance from the entity object identity, and uses ejbRemove()
to remove the entity object.
When the instance is put back into the pool, it is no longer associated with an entity
object identity. The container can now assign the instance to any entity object within the
same entity bean home.
A more thorough discussion can be found in the EJB 1.1 specification by Sun.
To complete a transaction, which Transaction Attributes or Isolation Level should be used for a
stateless session bean?
[For example, I have a method transfer which transfers funds from one account to another account.]
Vague question. Is the Session bean doing the DB work? I'll assume no.
Let's say AtmEJB is a Session bean with the transfer method. Let's say AccountEJB is an
Entity bean.
Step 1:
When the client invokes the transfer method you want that to be the transaction; i.e.
"the transfer transaction". therefore you need to set the tx attribute of transfer to
something that will make the container start a tx at the beginning of transfer and
terminate it at the end of transfer. RequiresNew might be a good choice but you need to
look at all your use cases not just this one.
Step 2:
The AccountEJB methods invoked from the transfer method need to have a tx attribute
that allows them to be part of an ongoing tx. That means that deposit and withdraw
cannot be RequiresNew! (that would suspend the transfer tx and run in its own tx). Look
at the spec for these: there are 3 that meets the criteria for deposit and withdraw in the
transfer use case. Which one to use? What are the other use cases in which deposit and
withdraw will be called? Find one that works for each one.
Activation for an entity bean means "the container has just grabbed an anonymous
instance of the entity class from the free pool and has associated it with an identity".
Identity means a primary key stored in an EJBObject. Beans in the free pool have no
valid state since they are not associated with an EJBObject (and therefore a primary
key).There is no loading of state here. With BMP you load the state in ejbLoad; with CMP
the container does it right before ejbLoad.
Passivation for an entity bean means "the container is done with this instance and it is
going back to being an anonymous member of the free pool". There is no saving of state
here. With BMP you save the state in ejbStore; with CMP the container does it right after
ejbStore.
Mohan
EJB FAQ Page 28 of 36
Take a look at the EJB spec 1.1 on page 102. Figure 23 shows this is a pseudo Harel
state diagram. Also look at Figure 28, page 138 and Figure 29, page 139 for object
interaction diagrams.
Explain the different Transaction Attributes and Isolation Levels with reference to a scenario.
The Enterprise JavaBeans model supports six different transaction rules:
Are there any good examples of how to handle one-to-many, many-to-one, and many-to-many
entity bean relationships?
The EJB spec does not specify how to deal with relationships. You'll have to develop your own Java classes
to handle these design patterns.
Which IDEs are available that support EJB development? And are any free or low-cost?
We've been doing some review of WebGain's StructureBuilder 3.3, which supports a UML-to-Javacode
cyclical development, and with its new "ejbCreate" facility, supports 1.0 and 1.1 EJB development. So far,
we're thoroughly impressed. A little clunky/slow, but definitely worth investigating for lower cost (standard
$395, enterprise $695) bean development.
Mohan
EJB FAQ Page 29 of 36
A fully functional demo is available at
http://www.webgain.com/Products/Structure_Builder/.
What is the most efficient approach for integrating EJB with JSP? Should the EJBs be invoked
directly from within JSP scriptlets? Should the access take place from within Java beans? Or is
it best to use custom tags for this purpose?
JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in many lines of
code on your JSP page, including try...catch blocks to catch naming and finding exceptions.
Using a standard JavaBean as an intermediary between the JSP page and EJB server
cuts down on the amount of code needed to add to a JSP page, and promotes reuse. The
JavaBean should be a simple wrapper around the EJB you are accessing.
If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB
parameters, such as the server URL and server security parameters.
Custom tags are also an option. However, they require a lot more coding than a simple
JavaBean wrapper. The point should be to rewrite as little code as possible while at the
same time keeping the JSP scriptlet content as light as possible.
How do you get a JDBC database registered with a JNDI name so that it can be accessed from
an EJB?
The short answer is that it depends on which container you're using to some extent. The one thing that
(should be) common in EJB 1.1 containers is that the ejb-jar.xml file's entry for that bean needs to
contain a 'resource-ref' stanza, like so:
<resource-ref>
<res-ref-name>jdbc/LocalDB2<res-ref-name>
<res-type>javax.sql.DataSource<res-type>
<res-auth>Container<res-auth>
<resource-ref>
The res-ref-name is the most interesting part. This is the JNDI name relative to the
java:comp/env namespace. Hence, to get this connection you'd do (in your bean):
Context context = new InitialContext();
DataSource source =
context.lookup("java:comp/env/jdbc/LocalDB2");
which gives you a DataSource that you can call getConnection on.
The other half of this is container specific and done at deployment time by a 'Deployer'
or 'Assembler' (to use the rolenames specified by the EJB spec.) This can work very
differently from one container to the next, but here are a couple of (abbreviated)
examples.
With Weblogic 5.1, you must define a connection pool in weblogic.properties, then edit
the weblogic specific deployment descriptor (using the EJB Deployment tool) to associate
the resource-ref specified in ejb-jar.xml with that connection pool.
With Inprise Application Server 4.0, all of the parameters for the connection (JDBC
driver, connection URL, etc.) are specified in the inprise specific deployment descriptor
(also editable via their deployment tool).
Other servers will have other ways of associating the resource-ref with a pre-defined
connection pool.
How to manage fields that can have null values in a container-managed Entity bean?
First of all, let's just set up a typical scenario:
You are developing a product which allows a bank to sign up new customers online. You
have done analysis and design and settled on having two tables: 'users' and 'account'
(let's keep it simple). Each "user" will have a corresponding "account". The foreign key
between the two will be the "account number".
So, for the 'users' table, you have the following fields: firstName, lastName, userId,
password, and acctNum. When this table is created in the database, it is empty. Now
you must relate your EJB code to this table for persistence. For simplicity sake I will
leave out the Session bean (which I would use to talk to my Entity bean), the Entity
bean primary key class, and the home and remote interfaces.
/**
* Called by the container after the UserHome.create () is called
*/
public void ejbCreate(String userId, String password, long acctNum)
{
this.userId = userId;
this.password = password;
this.acctNum = acctNum;
}
...
...
public void setUserData(UserData data) throws RemoteExeption, UserDataException
{
this.firstName = data.getFirstName();
this.lastName = data.getLastName();
}
...
...
}
Now, assuming you have the User (remote interface class), UserHome (home interface
class), UserPK (primary key class) already done, you need to create the bean's
deployment descriptor. Inside the deployment descriptor, you must specify the database
table, 'users', which this bean will map to. Also, you must specify which fields from your
bean map to which fields in the 'users' database table. (This is how the container knows
which fields to persist between your bean and the database table.) Now assuming all
code compiles and you have an EJB server up and running and you have deployed your
bean, all you need to do is write a client (I would use a client to access a session bean,
say 'CustomerSession', which would talk to my entity bean) to create a new user and
pass in the userId, password and acctNum values, which will create the new user in the
database.
Notice the fields in the UserBean will now be set, but the firstName and lastName fields
will still be set to null. These fields will still be empty in the database and will not change
until these fields are set in the bean, since it is persisted. Now, call the
setUserData(UserData data) method for setting the firstName and lastName, and these
fields will now be set in the database and no longer be null. The container will handle the
persistence of any fields which are set to null, just as it will handle any fields which are
set to some meaningful value.
Borland's JBuilder 3.5, Foundation Edition allows you to debug any Java 2 application,
including the Inprise Application Server, WebLogic Server and J2EE Reference
implementation. You can download it free from www.borland.com/jbuilder.
There are other IDE's out there including NetBeans/Forte www.sun.com/forte/ffj/ce/ that
can also debug EJB.
This means that the J2EE and/or JNDI and/or RMI classes need to be present in the
applet's Java Virtual Machine. The easiest way to assure this is to use the latest Java
Plug-in. Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have
various problems with RMI and JNDI classes that are beyond the scope of this answer.
Note, however, that it is not recommended to use EJB directly from applets, in part due
to compatibility issues. Instead, you can use Servlets inside the application server to
provide an HTML front-end that is assured to work on a much larger base of clients.
Mohan
EJB FAQ Page 31 of 36
What is the best way of implementing a web application that uses JSP, servlet and EJB
technologies all together following a Model View Controller (MVC) architecture?
Hmm, 'Best Way' is a bit rough - there are several 'good' ways, and the usual set of trade-offs between
them. (I'm a consultant - I have to start any answer with "It depends...", otherwise they revoke my
whiteboard privileges)
The main thing you need to keep in mind as you design this sort of a system is that you
want the interface into the EJB's to be rather narrow: in any flow, the ideal is to call one
EJB method (hopefully on a stateless session bean), and let it make calls to entities on
your behalf, then hand back the data you need to display.
How you display it depends: you can either embed beans on your JSPs and let the beans
make that hopefully-one EJB call, or you can post to a servlet, let that make the call,
then forward to the JSP for display. The second of these is more flexible and gives you
more leverage to hide, change, and enforce your site's structure. The first, however, will
be easier for developers new to this web thing to follow.
Essentially, I'm saying that Entity beans are your model, your controller is Session
beans (maybe with a bit of help from servlets or beans), and your JSPs, beans and
servlets are your View.
One thing to note here: this discussion strongly implies that your EJBs are capable of
externalizing their state as some number of very simple 'value objects' (not EJBs
themselves, just something we can pass back and forth). These value objects are
probably tuned tightly to a workflow, and will be produced by that session bean. This
way the traffic between the EJB (server) and the JSP/Servlet (client) is tuned to what
the client needs, while the transaction load on the server is minimized.
For other books that are relevant to JNDI, check out Are ther any books that provide
decent JNDI coverage?.
When does the container call my bean's ejbCreate / ejbPostCreate / ejbStore / ejbPassivate /
ejbActivate / ejbLoad / ejbPassivate method? And what should I do inside it?
The lifecycle of an enterprise bean is the heart of the EJB system. Your bean is basically implemented as a
set of callback methods. There are a lot of these methods, which can be confusing; however, the
implementation of each one is actually quite straightforward. Most of the time you can get away with
implementing only a few of them.
Using Bean-Managed Persistence, each callback method ejbX means the obvious thing
(usually "you must do X").
• ejbStore means "I'm about to store your data into the DB"
• ejbPassivate means "I just stored your data, and I'm about to passivate you"
• ejbActivate means "I just activated you, and I'm about to load in your data"
• ejbLoad means "I just loaded your data from the DB"
The following table is based on the EJB Spec 1.1, chapter 9, section 5. Section 9.4 and
9.5 has detailed descriptions of each of the callbacks; you should definitely read the
spec, and use the table as a quick reference only.
Initialization:
What's the difference between EJBHome, EJB Home, EJB Object, EJBObject and EJB (not to
mention Home Interface and Remote Interface)?
The EJB spec is all about really bad naming decisions.
First, an Enterprise JavaBean is not a JavaBean (but you already knew that).
When you write the source code for the EJB Home Interface, you must extend the
interface EJBHome, and provide method signatures for all the desired create() and
find() methods. An object that implements the Home Interface is automatically
generated by the EJB Server tools.
The "EJB Object" , or Remote Object, is actually a Wrapper. It sits somewhere inside
the container, between the client and your code. It is responsible for performing all the
setup and shutdown tasks (like opening transactions, or restoring data state)
immediately before and after your enterprise bean is called.
The "EJB Object" is generated by the EJB Server tools -- you don't have to write any
part of it. However, you do have to write another interface, called the "Remote
Interface" or the "EJBObject Interface," that extends interface EJBObject, and
provides method signatures for all the business methods. The server automatically
generates a Java class that implements the Remote Interface; it is this object that is
registered with RMI, and a reference to it is returned by the Home Interface (which we
now know is actually a Factory Object).
Mohan
EJB FAQ Page 33 of 36
The "EJB," or Enterprise Bean, ironically, is not the EJB Object (even though it is an
EJB and it is an object). It doesn't even implement the EJBObject interface, nor does it
implement the Remote Interface. Instead, it implements either the EntityBean interface
or the SessionBean interface. It also must implement all the methods defined in the
Remote Interface -- but it doesn't actually implement the interface (in the Java sense).
This is unfortunate, since we cannot rely on the Java compiler to make sure we've
implemented all the right methods. It must also implement one ejbCreate() method for
each create() method in the Home Interface (as well as ejbFind()/find()).
Can the security context be passed between a web container (servlets/jsp) and an EJB
container ? When the servlet calls an EJB I want its identity to be that of the original web client
authenticated with a certificate.
The whole issue of propagation of authentication context from client to the EJB server is still evolving -
both in terms of the specification as well as vendor offerings. According to the current Java 2 specification
(page 224):
The only recommendation is that you must have a "powerful" machine with at least
128MB of RAM (better 192MB for 5.1.0) and a 400MHz processor (or above)...
Is there a difference between container managed and bean managed persistence in terms of
performances?
[Short answer: with bean-managed persistence, you can optimize your queries and improve performance
over the generalized container-managed heuristics. But container-managed persistence is very
convenient, and vendors will be working to improve its performance as time goes on. -Alex]
There is of course a difference as many CMPs use O-R mapping using metadata, which is
slower than hardcoded queries (except vendors like GemStone that use a OODB which is
slow anyway!) As always, a lot depends on the database schema. Given that CMP is still
evolving, complex relationships (e.g.inheritance) and distributed transactions are not
even supported by most EJB server vendors, leave alone performance.
Having said that however, it does not seem right to compare BMP and CMP on
performance because the motivation of CMP is precisely to relieve bean providers from
thinking about this! In (J2EE) theory, a good CMP implementation should perform well in
a production environment; in practice, except for a couple of vendors who have
traditionally been strong in persistent storage space (e.g. Persistence Software,
GemStone) you will not find great CMP support at this very moment.
BMP offers a tactical approach while CMP is more strategic. Which implies that if you can
work-around some (perhaps severe) limitations for near-term, there may be much to
gain with CMP as the vendor offering matures.
Mohan
EJB FAQ Page 35 of 36
Given that RMI-IIOP does not support distributed garbage collection (unlike RMI-JRMP), do I
need to do something explicitly to GC beans, or is it magically handled by the EJB framework?
It is the Containers' responsibility to handle distributed garbage collection. This is how EJB's were
designed.
Looking at Stateful Session Beans (SFSB) or Entity Beans. When you write a SFSB, you
must implement ejbActivate () and ejbPassivate(). Implementing these methods, mean
that the container can passivate your bean, hence take it out of memory and store its
state on disk or in a datastore somewhere.
Whilst this article does take a hit at EJB, I believe that it is misleading in some sense
and is outdated. Most of the pot shots that it takes about EJB products not supporting
latest standards etc. are now obsolete as vendors such as Inprise, BEA, GemStone etc.
have updated there products, it's a shame that he didn't get to review the beta
products...
The article also mentions the importance of "Dynamic Glue" which is not using statically
generated stubs and skeletons. This is in fact possible with RMI-IIOP using DII (Dynamic
Invoacation Interface), but he fails mention how this technology is used in building
systems and why it is important. He says that it is why CORBA has failed, which is
wrong. EJB is a logical extension of and most Containers are built on top of CORBA.
He also mentions the overheads of intra-vm calls. This is something that most products
provide optimizations for and something he clearly hasn't researched as this is a feature
that CORBA ORB's have supported for quite a while.
OK, so EJB doesn't support user-created threads. So how do I perform tasks asynchronously?
If your EJB does not need to know about the results of the aynch calls, then you can use JMS to send an
asynch. message to another part of the system.
Another alternative is to place the multithreaded code inside a CORBA or RMI server and
call this from your EJB. Always keep site of the big picture, RMI and CORBA are part of
J2EE and can be used as part of a 'J2EE' solution.
There are some things that these technologies can do that EJB at this present time
cannot.
My session beans call other bean methods within a transaction. Using bean-managed transactions, how
should I take care of commit and rollback ?
There are two steps here:
1. Coding step:
public class exBean implements SessionBean
{
EJBContext ec;
javax.transaction.UserTransaction utxn;
.
.
.
utxn = ec.getUserTransaction();
ut.begin();
// do all you txn stuff - getting DB connections, updates, other bean methods, etc.
.
.
ut.commit();
}
Note you have to begin a txn before opening dB connections and close connections
before committing.
2. Deployment step:
- Your app server must support a JTS for distributed txns. Most do.
Mohan
EJB FAQ Page 36 of 36
- Verify there is no conflict with the bean transaction properties in calling beans.
Mohan