Enterprise JavaBeans FAQs

What is Enterprise JavaBeans?
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.

What's so special about Enterprise JavaBeans?
Enterprise JavaBeans simplifies the task of developing distributed objects systems. It's easier for developers to create transactional distributed object applications with EJB than with any other Java based component architecture. With Enterprise JavaBeans, transactions, security, and persistence can be handled automatically allowing developer to focus on the business logic.

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.

What is a session bean?
A session bean is a type of enterprise bean; a type of EJB server-side component. Session bean components implement the javax.ejb.SessionBean interface and can be stateless or stateful. Stateless session beans are components that perform transient services; stateful session beans are components that are dedicated to one client and act as a server-side extension of that client.

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.

What is a CMP bean?
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.

What is a BMP bean?
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.

Are Enterprise JavaBeans and JavaBeans the same thing?
Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the other. They are both component models, based on Java, and created by Sun Microsystems, but their purpose and packages (base types and interfaces) are completely different.

How does a client application create a transaction object?
For a servlet or other clients 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()
  ...
JNDI remote look-up names and property names vary, of course, across servers/environment.

Why would a client application use JTA transactions?
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.

How does a session bean obtain a JTA UserTransaction object?
A session bean can obtain a UserTransaction object via the EJBContext using the getUserTransaction() method.

How does an enterprise 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 a session bean for bean-managed transactions?
You must set transaction-type in the deployment descriptor.

How does an entity bean obtain a JTA UserTransaction object?
It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always employ declarative, container-managed transaction demarcation.

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 can my JSP page communicate with an EJB Session Bean?
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...
%>

Alternatively you can use a Java Bean to call EJB instead of writing the code in JSP.

How do enterprise beans access native libraries?
They can NOT access native library.

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.

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;

public interface EJBMetaData {
 // Obtain the home interface of the enterprise Bean.
   public EJBHome getEJBHome();
   //Obtain the home interface of the enterprise Bean.
   java.lang.Class getHomeInterfaceClass();
   //Obtain the Class object for the enterprise Bean's home interface.
   java.lang.Class getPrimaryKeyClass();
   //Obtain the Class object for the enterprise Bean's primary key class.
   java.lang.Class getRemoteInterfaceClass();
   //Obtain the Class object for the enterprise Bean's remote interface.
   boolean isSession();
   //Test if the enterprise Bean's type is "session".
   boolean isStatelessSession();
}

Once a client application has a reference to bean's remote and home interface classes, normal Java reflection can be used to introspect the methods avaiable to client. Below is an example:

Class remoteClass = ejbMetaData.getRemoteInterfaceClass();

java.lang.reflect.Method [] methods = remoteClass.getDeclaredMethods();

for(int i = 0; i  methods.length; i++){
	System.out.println(methods[i].getName());

}

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.

Does the EJB programming model support inheritance?
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.

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.

Should synchronization primitives be used on bean methods?
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.

What classes does a client application need to access EJB?
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:

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.

What's an .ear file?
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). 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.

Is method overloading allowed in EJB?
Yes you can overload methods.

Can primary keys contain more than one field?
Yes, a primary key can have as many fields as the developer feels is necessary, just make sure that each field you specify as the primary key, you also specify a matching field in the bean class. A primary key is simply one or more attributes which uniquely identify a specific element in a database. Also, remember to account for all fields in the equals() and hashCode() methods.

What happens when two users access an Entity Bean concurrently?
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.

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.

What are the differences between EJB 1.1 and EJB 2.0?
There are many differences, all of them should give different type of advantages among the previous 1.1 version.

What are the additional features of EJB 2.1 over EJB 2.0
Compared to the 2.0 specifications, EJB 2.1 have focused the attention in trying to be more "web-services" oriented, and the addition of a Timer service.

The biggest addition in EJB 2.1 is the new support for the Web-Services technology. With this new specifications, in fact, developers can expose their Stateless Session and Message-Driven EJBs as Web Services based on SOAP. This will mean that any client that complies with SOAP 1.1 will be able to access to the exposed EJBs. The APIs that will allow this and that have been added, are JAXM and JAX-RPC.

Another addition is the Timer Service, that can be seen as a scheduling built right inside the EJB Container. With EJB 2.1, any Stateless Session or Entity Bean can register itself with the Timer Service, requesting a notification or when a given timeframe has elapsed, or at a specific point in time. From a developer point of view, the Timer Service uses a very simple programming model based on the implementation of the TimedObject interface.

From the enhancement side, the Query Language is definitely the topic where the improvements are definitely more visible. The ORDER BY clause has finally been added. This will improve performance on orederd queries, because this will be handled by the underneath database, and not through the code by sorting the resulting collection.

The WHERE clause has been improved with the addition of MOD, while the SELECT clause has been improved by adding aggregate functions, like COUNT, SUM, AVG, MIN and MAX.

Both RMI and EJB are distributed applications.In EJB we use Home interface which is not avaliable in RMI?
RMI is a lower level technology that allows java objects to be distributed across multiple JVMs. Essentially, RMI abstracts sockets and inter-JVM communications.

EJB, on the other hand, is a technology built atop of RMI but does so much more than allow java objects to be distributed. It is a framework that allows you to build enterprise applications by (among other things) abstracting transactions, database access and concurent processing.

The home interface is EJB's way of creating an object. Home interfaces act as factories to create session beans and entity beans. These factories are provided by the application container and take care of many low level details. Since RMI is a lower level technology, it does not offer the home interface. You would have to create it yourself.

How many EJB Objects are created for a Bean
There is absolutely no relationship between the amount of EJBObjects you create on the client side and the amount of bean instances that actually exist on the server side.

When a client invokes a method on the stub, the container will look into the bean pool and see if there are any available bean instances that can satisfy that request. It will create more instances if all instances are currently being used by other clients.

You can control the size of the pool thru the deployment descriptor.

What is session facade?
Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design.

Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction.

As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.

The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.

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.

What is the diffrence between ejbCreate() and ejbPostCreate() in EntityBean?
ejbCreate() is called before the state of the bean is written to the persistence storage (database). After this method is completed, a new record (based on the persistence fields) is created and written. If the Entity EJB is BMP, then this method must contain the code for writing the new record to the persistence storage.

ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an EJB object, so when the bean is available. In an CMP Entity EJB, this method is normally used to manage the beans' container-managed relationship fields.

Can a primitive data type be specified as a method parameter, in the deployment descriptor?
There are no specific restriction for using Java primitive types in the tag in the Deployment descriptor.

If you are using classes, use fully qualified class name such as java.lang.String and not just String.


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

How can i get user name from inside inside EJB.
Inside an EJB you may retrieve the "Caller" name, that is the login id by invoking:

ctx.getCallerIdentity().getName()

Where ctx is the instance of "SessionContext" passed to the Session Bean, or the instance of "EntityContext" passed to the Entity Bean.

How is Stateful Session bean maintain their states with client?
When a client refers to a Stateful Session object reference, all calls are directed to the same object on the EJB container. The container does not require client identity information or any cookie object to use the correct object. This means that for a client to ensure that calls are directed to the same object on the container, all it has to do is to use same reference for every call.

Thus, if you're calling a Stateful Session Bean from a servlet, your servlet need to keep the reference to the remote object in the HttpSession object between client calls for you to be able to direct calls to the same object on the container. Likewise, if you're calling from an application, you only obtain the reference to the bean once and reuse the object throughout the application session.

With EJB 1.1 specs, why is unsetSessionContext() not provided in Session Beans, like unsetEntityContext() in Entity Beans?
ejbRemove()is called for session beans every time the container destroyes the bean. So you can use this method to do the stuff you typically would do in unsetEntityContext().

For entity beans ejbRemove() is only called if the user explicitly deletes the bean. I think that is the reason why the engineers at SUN invented the unsetEntityContext() for this kind of bean.

How u map a composite Primary Key in CMP Entity Bean and how u handle the same composite primary key in primary key class? What is the usage of HashCode() and Equals() methods? They return only one single primary key value?
equals() returns a boolean that indicates whether another object is "equal" to this one, while hashCode() returns an int that represent the hashcode of an object, that is used for the benefit of hashtables, like java.util.Hashtable.

The reason why we have 2 methods is that hashcode may not always return unique values. So the container also calls the equals method to verify the uniqueness.

Implementing an EJB CMP compound primary key?
A Primary Key Class is a class that follows few simple rules:

<