You are on page 1of 22

EJB FAQ:

1) What is the default time for transaction manager? And how to set maximum
time(timeout) for transaction?.
The default time depends on your app server. It is usually around 30 seconds. If you are using
bean-managed transactions, you can set it like this:
// One of the methods from the SessionBean interface
public void setSessionContext(SessionContext context) throws EJBException
{
sessionContext = context;
}
// Then, when starting a new transaction
UserTransaction userTransaction = sessionContext.getUserTransaction();
userTransaction.setTransactionTimeout(60);
userTransaction.begin();
// do stuff
userTransaction.commit();
If you are using container-managed transactions, this value is set in a app server specific
way. Check your app server's deployment descriptor DTD.
2) Session Bean transactions.
Why EJB 1.1 specs says that Session Beans can have BM or CM transaction,
but not both in same bean?
CMTs and BMTs are 2 different animals. Mixing them in the same bean would require the
application container to potentially start a transaction at the beginning of the method while the
BMT bean itself would start another. Things could get quickly get out of hand.
Even mixing CMT beans and BMT beans in the same process flow can be tricky. For example, a
BMT bean cannot participate in transactions started by a CMT bean (although the opposite is
allowed).
The real is question is why would you need to do this? Most of the time, you will use CMTs.
BMTs are used in special circumstances where you need fine-grained transaction control.
3) If my session bean with single method insert record into 2 entity beans, how
can know that the process is done in same transaction (the attributes for
these beans are Required)?
If yor method in the session bean is already running under a transaction the calls to any other
bean which have been deployed with trans-attribute 'Required' will be executed within the
same transaction context.
So if your session bean is using container-managed transactions and your method is deployed
with 'Required', 'RequiresNew' or 'Mandatory', you can safely assume that the calls to your
entity beans are handled under same transaction. If you're not running in a transaction, a
separate transaction will be set up for each call to your entity beans.
If your session bean is using bean-managed transactions, you can ensure that the calls are
handled in the same transaction by :
javax.transaction.UserTransaction tran= null;
try{
tran=ctx.getUserTransaction();
tran.begin();

myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling
tran.getStatus().
4) The EJB specification says that we cannot use Bean Managed Transaction in
Entity Beans. Why?
Answer
The short, practical answer is... because it makes your entity beans useless as a reusable
component. Also, transaction management is best left to the application server - that's what
they're there for.
It's all about atomic operations on your data. If an operation updates more than one entity
then you want the whole thing to succeed or the whole thing to fail, nothing in between. If you
put commits in the entity beans then it's very difficult to rollback if an error occurs at some
point late in the operation.
Think of an account transfer which takes money from the first account and then pays it into a
second account. If the paying in part fails how do you put the money back in the first account?
What about if that then fails too?
The transaction should always "wrap" the entire operation. There are two obvious ways of
achieving this in an EJB environment:
1.
2.

Use the javax.transaction package


Use a session bean to represent usecases and specify how transactions should be
managed as part of the session bean's deployment descriptor.

Solution 2 is the "correct" way to do it. Either way, you can simply leave all transaction code
out of your entity beans.
Any good EJB book will explain more about this.
Application Exception and EJB Transaction.
If I throw a custom ApplicationException from a business method in Entity bean
which is participating in a transaction, would the transaction be rolled back by
container? Does container rolls back transaction only in case of SystemExceptions?
Answer
The short answers are: No and Yes.
A SystemException is a subtype of java.lang.RuntimeException, while an
ApplicationException is any Exception that does not extends neither
java.lang.RuntimeException nor java.rmi.RemoteException.
Said so, we have to add that an EJB Transaction is automatically rolled back only when a
SystemException (or a subtype of it) is thrown.
Question Are we allowed to change the transaction isolation property in middle of a
transaction?
Answer
No. You cannot change the transaction isolation level in the middle of transaction.

Why can't a Stateless SEssion Bean implement the SessionSynchronization


interface? it might also want to be notified of the transaction events.
It's just because a Stateless Session Bean does not have state. The container does not
guarantee (like for the Stateful SEssion Bean) that the bean that will be used on two method
calls, will be the same.
Question With regard to Entity Beans, what happens if both my EJB Server and
Database crash, what will happen to unsaved changes? Is there any
transactional log file used

Any unsaved and uncommited changes are lost the moment your EJB Server crashes. If
your database also crashes, then all the saved changes are also lost unless you have some
backup or some recovery mechanism to retrieve the data. So consider database replication
and EJB Clustering for such scenarios, though the occurence of such a thing is very very
rare.
Question Is it possible to stop the execution of a method before completion in a
SessionBean
Answer
Stopping the execution of a method inside a Session Bean is not possible without writing code
inside the Session Bean. This is because you are not allowed to access Threads inside an EJB,
refer to section 18.1.2 of the EJB 1.1 specification.
One possible solution (that requires coding) would be to set the transaction that the Session
Bean is running within to be rolled back. To do this, use the setRollBackOnly() method of the
javax.transaction.UserTransaction interface. This method would of course require that
your Session Bean is using transactions.
If the Session Bean is processing many long running requests then it could provide an
optimization by checking the transaction status using the getRollBackOnly() call of the
javax.ejb.SessionContext object.
Question I am developing a BMP Entity bean. I have noticed that whenever I the
create method is invoked, the ejbLoad() and the ejbStore() methods are
also invoked. I feel that once my database insert is done, having to do a
select and update SQL queries is major overhead. is this behavior typical
of all EJB containers? Is there any way to suppress these invocations?
This is the default behaviour for EJB. The specification states that ejbLoad() will be called
before every transaction and ejbStore() after every transaction.
Each Vendor has optimizations, which are proprietary for this scenario. We will outline the
properties for the popular servers below:
WebLogic 5.1
1.

The db-is-shared option, which is set in the weblogic-ejb-jar.xml file. This option by
default set to true, but can be overridden. This option can be used if the WebLogic
Server has exclusive access to the database. Using this option ejbLoad()will be called
only once when the user obtains remote interface and then after any transaction
rollback. This cannot be used in a cluster

2.

3.

The Cache Strategy option can be set to read-only. Using this strategy the Container
will never invoke ejbStore() and will limit calls to ejbLoad() as specified by the readtimeout-seconds options. Both options are also set in the weblogic-ejb-jar.xml file.
The is-modified-method-name option, which is set in the weblogic-ejb-jar.xml file and
is used to specify a method that the container will invoke before ejbStore(). If this
method returns true then ejbStore() will be called, if it returns false, then it will not
invoke ejbStore

Question For session beans, we can use the SessionSynchronization interface. For
entity beans, how do we have control over a transaction?
The SessionSynchronization interface is used by the Session beans to Synchronize the
Instance variables after a rollback or after a commit operation, because container does not
have any other way to inform the bean of these operations.
With Entity beans, this is not a problem as the Container automatically calls the ejbLoad
method that refreshed the values from the database.

Question Is it possible to get notified somehow if a certain amount of time elapses


during (within) a transaction or method call? I want to react if e.g. an
EJB-method doesn't react after a few seconds.
Answer
The EJB descriptor defined session timeout (sessionTimeout in the WebLogic descriptor)
will cause the remote call to throw an exception if the operation runs over that time. This
will cause the operation to be rolled back if it is running in a transaction, but the caller will
be notified by the exception so you can react accordingly.
Question How do the six transaction attributes map to isolation levels like "dirty
read"? Will an attribute like "Required" lock out other readers until I'm
finished updating?
Answer
The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC.
This is a common misconception.
Transaction Attributes specify to the container when a Transaction should be started,
suspended(paused) and committed between method invocations on Enterprise JavaBeans.
For more details and a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1
specification.
Question

How do I insert or update 2 different Entity Beans within the same


transaction?

Answer
To easily achieve this, you can call both inserts from another bean, for example a Session
Bean (if you are using the standard Session wraps Entity design pattern).
Lets say that both Entity Beans have defined create methods, and that the Session Bean has a
method called insertEntities(). Inside the insertEntities() method, you would obtain handles to

the approriate home interfaces and call create on each one. The trick here is on how you set
up the transaction attributes.
You would like both of your Entity Beans to share the same transaction, and in this example,
we can have the Session Bean as the initiator of the transaction.
If we set the insertEntites() method to have a Transaction Attribute of REQUIRED or
REQUIRES_NEW, then we assure that a transaction will be present. (REQUIRED is generally
more robust, since it allows this insertEntities() call to be part of an ongoing, larger
transaction, but if one is not in progress, a new one will be created.) If we then set the
Transaction Attributes for each of the Entity Beans to REQUIRED, then the same Transaction
Context will be propagated from the Session Bean to both Entity Beans, achieving the result
you are after.
[Note that this works no matter which Persistence method (CMP or BMP) the Entity Beans
use.
Question Can I use the afterBegin, beforeCompletion, and afterCompletion methods
in a BMP bean? (as these are the methods of the SessionSynchronization
interface)
Answer
The spec says no. Really, (IMHO) these don't translate well to the life of an entity bean for the
following reasons:
afterBegin might not mean much since the entity might join the transaction long
(computerwise) after the transaction is started.
Anything an entity bean needs to do 'beforeCompletion' should be done in ejbStore.
An entity bean really can't do much 'afterCompletion' - by definition, the entity's state
is already wherever it needs to be (database, queue, legacy system, etc.)
You might want to re-evaluate what you're actually trying to do: chances are you're
missing a key abstraction in your model.
Question My session beans call other bean methods within a transaction. Using
bean-managed transactions, how should I take care of commit and
rollback ?
Answer
There are two steps here:
1. Coding step:
public class exBean implements SessionBean {
EJBContext ec;
javax.transaction.UserTransaction utxn;
.
.
.
utxn = ec.getUserTransaction();
utxn.begin();
// do all your txn stuff
// getting DB connections, updates, other bean methods, etc.
.
.
utxn.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.
- Verify there is no conflict with the bean transaction properties in calling beans.
Question Explain the different Transaction Attributes and Isolation Levels with
reference to a scenario.
Answer
The Enterprise JavaBeans model supports six different transaction rules:

TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the enterprise


bean manually manages its own transaction control. EJB supports manual transaction
demarcation using the Java Transaction API. This is very tricky and should not be
attempted without a really good reason.

TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the enterprise


bean cannot execute within the context of a transaction. If a client (i.e., whatever
called the method-either a remote client or another enterprise bean) has a transaction
when it calls the enterprise bean, the container suspends the transaction for the
duration of the method call.
TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean can run
with or without a transaction context. If a client has a transaction when it calls the
enterprise bean, the method will join the client's transaction context. If the client does
not have a transaction, the method will run without a transaction.
TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean must
execute within the context of a transaction. If a client has a transaction when it calls
the enterprise bean, the method will join the client's transaction context. If the client
does not have a transaction, the container automatically starts a new transaction for
the method. Attributes
TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the enterprise
bean must execute within the context of a new transaction. The container always
starts a new transaction for the method. If the client has a transaction when it calls
the enterprise bean, the container suspends the client's transaction for the duration of
the method call.
TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise bean must
always execute within the context of the client's transaction. If the client does not
have a transaction when it calls the enterprise bean, the container throws the
TransactionRequired exception and the request fails

Question To complete a transaction, which Transaction Attributes or Isolation Level


should be used for a stateless session bean?
Answer
[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.
Question When should I use bean-managed transactions instead of specifying
transaction information in the deployment descriptor?
The Sun J2EE EJB Guide says like this:
Although beans with container-managed transactions require less coding, they
have one limitation: When a method is executing, it can be associated with
either a single transaction or no transaction at all. If this limitation will make
coding your session bean difficult, you should consider using bean-managed
transactions.
The following pseudo-code illustrates the kind of fine-grained control you can
obtain with bean-managed transactions. By checking various conditions, the
pseudo-code decides whether to start and stop different transactions within
the business method.
begin transaction
...
update table-a
...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c
commit transaction
...
I think what it means is there are some limitations in j2ee transaction support. In a container
managed situation, nested or multiple transactions are not allowed within a method. if a biz
method needs those features you need to go for bean managed transactions.
Question
Topics

What happens when two users access an Entity Bean concurrently?


Java:API:EJB:EntityBean, Java:API:EJB:Transactions

Answer
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.)

Question

Is entity data persisted at the end of a transaction or at any time?

Topics

Java:API:EJB:EntityBean, Java:API:EJB:Transactions

Author

Sameer Tyagi

Created

Jan 16, 2000

Modified

Aug 3, 2000

Answer
Depends on what you mean by "persisted". Data that is part of a transaction like database
rows are persisted depending on the success of the transaction. If the transaction manager
determines that the transaction was successful or there were no problems during any of the
steps invoved in it, the data is committed, or otherwise rolled back.
The container, on the other hand, invokes certain state transition lifecycle methods to conserve
resources. This involves passivation and activation of the bean or instance swapping. This
happens independent of the transaction since the client never interacts directly with the bean
instance but with the server's implementation of the EJBObject.
Question Is an EJB, JMS, or general-purpose Java application server a transaction
manager?
Topics

Java:API:JMS, Java:API:JMS:Transactions, Distributed


computing:Transactions, Distributed computing:Transactions:JTA,
Distributed computing:Transactions:JTS, Distributed
computing:Transactions:Application server, Distributed
computing:Transactions:Transaction manager,
Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
It depends on the server implementation. The JTA and JTS specifications define client-,
application-, and transaction manager-level operations. There is nothing to prevent a Java
application server from implementing, JMS, EJB, and JTS functionality. On the other hand, it
could (if available) obtain transaction manager services indirectly from another server.

Question Is it necessary for an entity bean to protect itself against concurrent


access from multiple transactions?
Topics

Java:API:EJB:EntityBean, Distributed computing:Transactions,


Distributed computing:Transactions:Concurrency,
Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
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.]
Question How does an entity bean obtain a JTA UserTransaction object?
Topics

Java:API:EJB:EntityBean, Distributed computing:Transactions,


Distributed computing:Transactions:JTA, Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always employ
declarative, container-managed transaction demarcation. Entity beans, by definition, are
somewhat tightly coupled (via the EJB container and server) to a datastore; hence, the EJB
container is in the best position to manage transaction processing.
Question How do you configure the transaction characteristics for a session bean
with container-managed transactions?
Topics

Java:API:EJB:SessionBean, Distributed computing:Transactions,


Java:API:EJB:Transactions, Java:API:EJB:Deployment Descriptor

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 24, 2000

Answer
You must set trans-attribute in the deployment descriptor.
Question How do you configure a session bean for bean-managed transactions?
Topics

Java:API:EJB:SessionBean, Distributed computing:Transactions,


Distributed computing:Transactions:JTA, Java:API:EJB:Transactions,
Java:API:EJB:Deployment Descriptor

Author

Jerry Smith PREMIUM

Created
Answer

Dec 14, 1999

Modified

Aug 24, 2000

You must set transaction-type in the deployment descriptor.


Question Is it possible for a stateless session bean to employ a JTA
UserTransaction object?
Topics

Java:API:EJB:SessionBean:Stateless, Distributed
computing:Transactions, Distributed computing:Transactions:JTA,
Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
Yes, but with restrictions. By definition, a stateless session bean has no state; hence, each
method invocation must be independent. (The bean can be "swapped out" between method
invocations.) Thus, a stateless session bean can obtain a UserTransaction object via the
EJBContext using the getUserTransaction() method, but it must start and finish each
transaction within the scope of a method invocation.
Question Why would a client application use JTA transactions?
Topics

Distributed computing:Transactions, Distributed


computing:Transactions:JTA, Distributed
computing:Transactions:Clients, Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
One possible example would be a scenario in which a client needs to employ two (or more)
session beans, where each session bean is deployed on a different EJB server and each bean
performs operations against external resources (for example, a database) and/or is managing
one or more entity beans. In this scenario, the client's logic could required an all-or-nothing
guarantee for the operations performed by the session beans; hence, the session bean usage
could be bundled together with a JTA UserTransaction object.
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.
Question Do JTS implementations support nested transactions?
Topics

Java:API:EJB:1.1, Distributed computing:Transactions, Distributed


computing:Transactions:JTA, Distributed computing:Transactions:JTS,
Distributed computing:Transactions:Transaction manager,
Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
A JTS transaction manager must support flat transactions; support of nested transactions is
optional. If a client begins a transaction, and within that transaction begins another
transaction, the latter operation will throw a NotSupportedException if the JTS implementation
does not support nested transactions.
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.
Question How does a client application create a transaction object?
Topics

Java:API:JMS:Transactions, Java:API:JMS:JNDI, Distributed


computing:Transactions, Distributed computing:Transactions:JTA,
Distributed computing:Transactions:Clients, Java:API:EJB:Transactions

Author

Jerry Smith PREMIUM

Created

Dec 14, 1999

Modified

Aug 3, 2000

Answer
How you gain access to UserTransaction objects varies depending on the type of client.
Enterprise JavaBeans provides two types of transaction management:

Container-managed transactions. As the name implies, the EJB container makes the
decisions (based on the deployment descriptor's trans-attribute setting) regarding how
to bundle operations into transactions and then works with the transaction manager,
which manages the transaction processing.
Bean-managed transactions. In this case, a session bean obtains the UserTransaction
object via the EJBContext using the getUserTransaction() method.

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

What is passivation and activation?

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Nov 22, 1999

Answer
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.
The java.ejb.SessionBean and javax.ejb.EntityBean interface include two callback methods that
notify a bean instance when it is about to passivated or activated. The ejbPassivate( ) method
notifies a bean that it is about to passivated; the ejbActivate( ) method notifies a bean that it
is about to activated.
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.
Question

What are the constraints or drawbacks of container managed EJB's ?

Topics

Java:API:EJB

Author

Sameer Tyagi

Created

Jan 15, 2000

Modified

Jan 16, 2000

Answer
CMP in beans depends a lot on the EJB vendor implementation and utilities. With some
implementations container-managed entity beans can only by mapped to one table, while
other implemenations offer Multiple table mappings to a single bean. The bottom line,It
depends on the container provider being used.

Question

How can my JSP page communicate with an EJB Session Bean?

Topics

Java:API:JSP, Java:API:EJB

Author

Govind Seshadri PREMIUM

Created

Jan 17, 2000

Modified

Jan 20, 2000

Answer
The following is a code snippet that demonstrates how a JSP page can interact with an EJB
session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
Question
Derived from

How do enterprise beans access native libraries?


A question posed by telmo sa

Topics

Java:API:EJB

Author

Tim Rohaly PREMIUM

Created

Jan 25, 2000

Modified

Jan 26, 2000

Answer
In short, they don't.
The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some things that
enterprise beans cannot do. In particular:

The enterprise bean must not attempt to load a native library.

This function is reserved for the EJB Container. Allowing the enterprise bean to
load native code would create a security hole.
The EJB 1.1 specification is available for download from
http://java.sun.com/products/ejb/docs.html.
Question

How do I implement a logging system in my beans?

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Jan 26, 2000

Modified

May 29, 2000

Answer
Using java.io is prohibited
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.
The EJB 1.1 specification is available for download from
http://java.sun.com/products/ejb/docs.html
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:
JDBC (javax.sql.DataSource) : Write log events in to a relational
database.
URL (java.net.URL) : Write log events to a custom logging server or
post them to a web server.
JavaMail (javax.mail.Session) : E-mail log events to a special
account
JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the log events as
messages.
Question
Derived from

When can we hope to see a comprehensive security spec for EJB?


A question posed by Roisin Parkes

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Feb 3, 2000

Modified

Feb 3, 2000

Answer
Currently the EJB security model supports authorization level security. Authorization security
or access control allows control over which users can invoke what methods on a bean. Access
control in EJB is declarative, which simplifies the programming model.
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
Question
Derived from

Does the EJB programming model support inheritance?


A question posed by James Webster

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Feb 4, 2000

Modified

Feb 4, 2000

Answer
Inheritance is supported in EJB in a limited fashion. Enterprise beans are made up of several
parts including: a remote interface; a home interface, a bean class (implementation); and a
deployment descriptor (see the FAQ What makes a Java class an enterprise bean? ).
The remote interface, which extends javax.ejb.EJBObject can be a subtype or a super-type of
remote interfaces of other beans. This is also true of the home interface, which extends
javax.ejb.EJBHome. The bean class, which implements either javax.ejb.EntityBean or
javax.ejb.SessionBean can also be a subtype or super-type of the bean class used by another
enterprise bean. Deployment descriptors are XML files, so there is no Object-Oriented (OO)
inheritance in the deployment descriptor.
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.
Question

How do I perform I/O operations from a bean?

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Feb 9, 2000

Modified

May 29, 2000

Answer
Using java.io is prohibited
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.

The EJB 1.1 specification is available for download from


http://java.sun.com/products/ejb/docs.html
Alternative Solutions
To perform I/O operations you must use 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:
JDBC (javax.sql.DataSource) : Write I/O data in to a relational
database.
URL (java.net.URL) : Write I/O data to a custom server or post them
to a web server.
JavaMail (javax.mail.Session) : E-mail I/O data to a special
account
JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the I/O data as
messages.
Question
Derived from

How should complex find operations be implemented?


A question posed by Joe McDaniel

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Feb 11, 2000

Modified

May 29, 2000

Answer
In bean-managed persistence (BMP) complex find operations are not difficult to implement,
because you have complete control over how a find operation works through the ejbFind
methods in the bean class. ejbFind methods in BMP entities can span multiple tables and even
different data sources to locate the right entity beans.
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.
Use a session bean to obtain the data you need. When a search
operation becomes to complex to implement in a single bean its a
good indication that the search operation is not appropriate for a find
method. Search operations that span the data encapsulated by several
different entity beans should be placed in a session bean with the
emphasis on returning only the data needed, not necessarily bean
references. Data can be returned in tabular format instead of bean
references.

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.
Question
Derived from

Should synchronization primitives be used on bean methods?


A question posed by suresh ramamoorthi

Topics

Java:API:EJB

Author

Greg Boettcher

Created

Feb 14, 2000

Modified

Feb 15, 2000

Answer
No. The EJB specification specifically states that the enterprise bean is not allowed to use
thread primitives. The container is responsible for managing concurrent access to beans at
runtime.
Question
Derived from

Can I use Threads in a enterprise bean?


A question posed by sanath sarma

Topics

Java:API:EJB

Author

Aravind Naidu

Created

Feb 15, 2000

Modified

May 22, 2000

Answer
No. The thread management is done by the container for you. As a bean developer you are
not allowed to use threads.
Section 18.1.2 of the EJB 1.1 specification states:

The enterprise bean must not attempt to manage threads. The


enterprise bean must not attempt to start, stop, suspend, or resume a
thread; or to change a threads priority or name. The enter-prise bean
must not attempt to manage thread groups.

These functions are reserved for the EJB Container. Allowing the enterprise
bean to manage threads would decrease the Containers ability to properly
manage the runtime environment.
Question
Derived from

How does EJB support polymorphism?


A question posed by sachin mahishi

Topics

Java:API:EJB

Author

Daniel Chong

Created

Feb 28, 2000

Modified

May 29, 2000

Answer
Because an EJB consists of multiple "parts", inheritance is achievable in a rather limited
fashion (see FAQ answer on inheritance here). There have been noteworthy suggestions on
using multiple inheritance of the remote interface to achieve polymorphism, but the problem
of how to share method signatures across whole EJBs remains to be addressed. The following
is one solution to achieving polymorphism with Session Beans. It has been tried and tested on
WebLogic Apps Server 4.50 with no problems so far.

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.

AnimalHome and Animal are the home and remote interfaces. The
signatures of the polymorphic methods are in Animal.
AnimalBean is the base implementation bean.
TigerBean and LionBean extend from AnimalBean. They may override
the methods of AnimalBean, implementing different behaviors.
Deploy Tiger and Lion beans, specifying AnimalHome and Animal as
their home and remote interfaces. Note that Tiger and Lion should
have different JNDI lookup names.

Question
Derived from

What classes does a client application need to access EJB?


A question posed by Sukumar Subbiah

Topics

Java:API:EJB

Author

Sameer Tyagi

Created

Mar 6, 2000

Modified

Aug 11, 2000

Answer
It is worthwhile to note that the client never directly interacts with the bean object but
interacts with distributed object stubs or proxies that provide a network connection to the EJB
container system.
The mechanhism is as follows.
1.
2.
3.

The client uses the JNDI context to get a remote reference (stub) to the home object (
the EJBHome).
It uses the home to get a remote reference (stub) to the EJBs remote object (the
EJBObject)
It then invokes business methods on this remote object.

The client needs the remote interface, the home interface, the primary key( if it is an entity
bean).
In addition to these, the client would need the JNDI factory implementation, and the remote
and home stubs. In some EJB servers the Factory and/or stubs can be dynamically loaded at
run time. In other EJB servers they must be in the classpath of the client application.
Question
Derived from

What's an .ear file?


A question posed by John Zukowski PREMIUM

Topics

Java:API:EJB, J2EE

Author

Mobushir Hingorjo

Created

Mar 6, 2000

Modified

Aug 4, 2000

Answer
An .ear file is an "Enterprise Archive" file. The file has the same format as a regular .jar file
(which is the same as ZIP, incidentally). The .ear file contains everything necessary to deploy
an enterprise application on an application server. It contains both the .war (Web Archive) file
containing the web component of the application as well as the .jar file. In addition there are
some deployment descriptor files in XML.

http://java.sun.com/j2ee/j2sdkee/techdocs/guides/ejb/html/Overview.fm.html contains
additional information.
Question
Derived from

Can beans use stored procedures in a database?


A question posed by Anil Datt

Topics

Java:API:EJB

Author

Richard Monson-Haefel

Created

Mar 10, 2000

Modified

Mar 10, 2000

Answer
Stored procedures can be used by session beans that access the database using JDBC and
bean-managed entity beans that use JDBC to manage their own persistence. JDBC provides a
call interface for using stored procedures. An example is provided below:
InitialContext cntx = new InitialContext( );
DataSource dataSource = (DataSource)
cntx.lookup("java:comp/env/jdbc/mydatabase");
Connection con = dataSource.getConnection( );
CallableStatement storedProcedure = con.prepareCall("{? = call
someprocedure [(?,?)]}");
Question
Derived from

Is method overloading allowed in EJB?


A question posed by Daniel Weimer

Topics

Java:API:EJB

Author

sachin mahishi

Created

Mar 24, 2000

Modified

Apr 3, 2000

Answer
Yes you can overload methods.
Question

How can one have non-client specific state in stateless session


beans?

Derived from A question posed by Alex Stouffs


Topics

Java:API:EJB

Author

sachin mahishi

Created

Apr 6, 2000

Modified

Apr 10, 2000

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

//all the SessionBean methods


public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
myprops = ctx.getEnvironment();
}
}
Question

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?

Derived A question posed by rajesh kkkkkkkkk


from
Topics

Java:API:EJB

Author

Robert Castaneda

Created

Apr 12, 2000

Modified

Apr 14, 2000

Answer
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.
Question

Can a bean act as a singleton to provide logging and other services?

Derived from A question posed by Diederik de Groot


Topics

Java:API:EJB

Author

Robert Castaneda

Created

Apr 12, 2000

Modified

Apr 14, 2000

Answer
No, You cannot implement a Singleton in EJB. A way to do this could be to implement an RMI
or CORBA object.
Question
Derived from

How do you implement callbacks in EJB?


A question posed by telmo sa

Topics

Java:API:EJB

Author

Robert Castaneda

Created

Apr 12, 2000

Modified

Apr 17, 2000

Answer
If your client is an EJB, it can pass a reference to itself to the method of the bean that it is
calling. The EJB can then call methods directly on that interface.

If your client is a Java client, your client requires some sort of object that will "listen" for callbacks. 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.
Question

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?

Derived A question posed by Benjamin Ghofrani


from
Topics

Java:API:EJB

Author

Robert Castaneda

Created

Apr 17, 2000

Modified

Apr 18, 2000

Answer
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.
Question

Which IDEs are available that support EJB development? And are any
free or low-cost?

Derived A question posed by DINESH DEWAN


from
Topics

Java:API:EJB

Author

Keir Hansen

Created

Apr 26, 2000

Modified

Apr 26, 2000

Answer
We've been doing some review of WebGain's StructureBuilder 3.3, which supports a UML-toJavacode 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.
Question

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?

Derived A question posed by Sanjay Mistry


from

Topics

Java:API:JSP, Java:API:EJB

Author

Christopher Longo

Created

May 1, 2000

Modified

May 2, 2000

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

You might also like