What Is an Enterprise Bean?
Written in the Java programming language, an enterprise
bean is a server-side component that encapsulates the business logic of an
application. The business logic is the code that fulfills the purpose of the
application. In an inventory control application, for example, the enterprise
beans might implement the business logic in methods called
checkInventoryLevel
and
orderProduct
. By invoking these
methods, remote clients can access the inventory services provided by the
application.
For several reasons, enterprise beans simplify the development of large, distributed applications. First, because the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container--not the bean developer--is responsible for system-level services such as transaction management and security authorization.
Second, because the beans--and not the clients--contain the application's business logic, the client developer can focus on the presentation of the client. The client developer does not have to code the routines that implement business rules or access databases. As a result, the clients are thinner, a benefit that is particularly important for clients that run on small devices.
Third, because enterprise beans are portable components, the application assembler can build new applications from existing beans. These applications can run on any compliant J2EE server.
You should consider using enterprise beans if your application has any of the following requirements:
The application must be scalable. To accommodate a growing number of users, you may need to distribute an application's components across multiple machines. Not only can the enterprise beans of an application run on different machines, but their location will remain transparent to the clients.
Transactions are required to ensure data integrity. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects.
The application will have a variety of clients. With just a few lines of code, remote clients can easily locate enterprise beans. These clients can be thin, various, and numerous.
Types of Enterprise Beans
Table 3-1 summarizes the three different types of enterprise beans. The following sections discuss each type in more detail.
Table 3-1 Summary of Enterprise Bean Types |
|
Enterprise Bean Type |
Purpose |
Session |
Performs a task for a client |
Entity |
Represents a business entity object that exists in persistent storage |
Message-Driven |
Acts as a listener for the Java Message Service API, processing messages asynchronously |
A session bean represents a single client inside the J2EE server. To access an application that is deployed on the server, the client invokes the session bean's methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.
As its name suggests, a session bean is similar to an interactive session. A session bean is not shared--it may have just one client, in the same way that an interactive session may have just one user. Like an interactive session, a session bean is not persistent. (That is, its data is not saved to a database.) When the client terminates, its session bean appears to terminate and is no longer associated with the client.
There are two types of session beans: stateful and stateless.
The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts ("talks") with its bean, this state is often called the conversational state.
The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state.
A stateless session bean does not maintain a conversational state for a particular client. When a client invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the duration of the invocation. When the method is finished, the state is no longer retained. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client.
Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.
At times, the EJB container may write a stateful session bean to secondary storage. However, stateless session beans are never written to secondary storage. Therefore, stateless beans may offer better performance than stateful beans.
A stateless session bean is an enterprise bean (EJB component) that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments.
The stateless session bean is an EJB component that
implements the javax.ejb.SessionBean
interface and is deployed with the declarative attribute "stateless". Stateless
session beans are called "stateless" because they do not maintain conversational
state specific to a client session. In other words, the instance fields in a
stateless session bean do not maintain data relative to a client session. This
makes stateless session beans very lightweight and fast, but also limits their
behavior.
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).
public class CreditService implements javax.ejb.SessionBean {
public Charge charge (String accountToCredit, CreditCard card, double amount)
throws ValidationException, RemoteException{
// attempt to obtain Merchant bean representing the retailer making the charge.
try{
MerchantHome mrchntHome = ... get VendorHome reference
Merchant merchant = mrchntHome.findByPrimaryKey(vendorToCredit);
}catch(ObjectNotFoundException onfe){
throw new ValidationException("Invalid merchant account number");
}
// attempt to create a Charge bean based on the vendor, amount, and credit card info
try{
ChargeHome chgHome = ... get ChargeHome reference
Charge charge = chgHome.create(merchant, card, amount);
return charge;
}catch(CreateException ce){
throw new ValidationException(ce.getMessage());
}
}
...
}
In the above example the
CreditService
bean method
charge( )
is completely
independent of the bean state or any other methods. The
charge( )
method is a stateless
service and the CreditService
bean
is a stateless bean. The charge( )
method uses two other bean types to process the charge. Its normal for stateless
beans to use other beans but they can also access the database directly or even
other resources like proprietary connections. Below is a list the beans used in
this example.
Bean Name |
Bean Type |
CreditService |
Stateless Session |
Merchant |
Entity |
Charge |
Entity |
In general, you should use a session bean if the following circumstances hold:
At any given time, only one client has access to the bean instance.
The state of the bean is not persistent, existing only for a short period of time (perhaps a few hours).
Stateful session beans are appropriate if any of the following conditions are true:
A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed.
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.
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
.)
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).
The bean's state represents the interaction between the bean and a specific client.
The bean needs to hold information about the client across method invocations.
The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
Behind the scenes, the bean manages the work flow of
several enterprise beans. For an example, see the
AccountControllerEJB
session bean
in Chapter 18.
To improve performance, you might choose a stateless session bean if it has any of these traits:
The bean's state has no data for a specific client.
In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an e-mail that confirms an online order.
The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month.
An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. In the J2EE SDK, the persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table. For code examples of entity beans, please refer to chapters 5 and 6.
What Makes Entity Beans Different from Session Beans?
Entity beans differ from session beans in several ways. Entity beans are persistent, allow shared access, have primary keys, and may participate in relationships with other entity beans.
Persistence
Because the state of an entity bean is saved in a storage mechanism, it is persistent. Persistence means that the entity bean's state exists beyond the lifetime of the application or the J2EE server process. If you've worked with databases, you're familiar with persistent data. The data in a database is persistent because it still exists even after you shut down the database server or the applications it services.
There are two types of persistence for entity beans: bean-managed and container-managed. With bean-managed persistence, the entity bean code that you write contains the calls that access the database. If your bean has container-managed persistence, the EJB container automatically generates the necessary database access calls. The code that you write for the entity bean does not include these calls. For additional information, see the section Container-Managed Persistence.
Shared Access
Entity beans may be shared by multiple clients. Because the clients might want to change the same data, it's important that entity beans work within transactions. Typically, the EJB container provides transaction management. In this case, you specify the transaction attributes in the bean's deployment descriptor. You do not have to code the transaction boundaries in the bean--the container marks the boundaries for you. See Chapter 14 for more information.
Primary Key
Each entity bean has a unique object identifier. A customer entity bean, for example, might be identified by a customer number. The unique identifier, or primary key, enables the client to locate a particular entity bean. For more information see the section Primary Keys for Bean-Managed Persistence.
Relationships
Like a table in a relational database, an entity bean may
be related to other entity beans. For example, in a college enrollment
application, StudentEJB
and
CourseEJB
would be related because
students enroll in classes.
You implement relationships differently for entity beans with bean-managed persistence and those with container-managed persistence. With bean-managed persistence, the code that you write implements the relationships. But with container-managed persistence, the EJB container takes care of the relationships for you. For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships.
Container-Managed Persistence
The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. In short, your entity beans are more portable.
In order to generate the data access calls, the container needs information that you provide in the entity bean's abstract schema.
When to Use Entity Beans
You should probably use an entity bean under the following conditions:
The bean represents a business entity, not a procedure. For
example, CreditCardEJB
would be an
entity bean, but CreditCardVerifierEJB
would be a session bean.
The bean's state must be persistent. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).
An entity bean is a type of enterprise bean; a type of EJB server-side component. Entity bean components implement the javax.ejb.EntityBean interface and can be container-managed (CMP) or bean-managed (BMP). Entity beans are designed to represent data in the database; they wrapper data with business object semantics and read and update data automatically.
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.
public class CustomerBean implements javax.ejb.EntityBean {
// persistent fields
public long customerNumber;
public Date lastActive;
public String lastName;
public String firstName;
// initialization method for creating a new customer
public CustomerKey ejbCreate(long id, PersonName name){
customerNumber = id;
setName(name);
lastActive = new Date();
return new CustomerKey(id);
}
// 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 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.
public class CustomerKey implements java.io.Serializable {
public long id;
public CustomerKey(long l)
{
id = l;
}
public int hashCode( ) {
return (int)id;
}
public boolean equals(Object otherKey){
if(otherKey instanceof CustomerKey)
return ((CustomerKey)otherKey).id == this.id;
else
return false;
}
}
You will notice that the business methods do not exactly match the persistent fields. This illustrates that the persistent state of the bean need not map exactly to the business methods, which provides more flexibility in how components are designed. For example, instead of having an accessor for lastName and firstName, the Customer bean uses a serializable PersonName to pass this information to and from the bean's client. In addition, you will have noticed that the lastActive can only be read by a bean client. The bean itself is responsible for updating this value.
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.
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.
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.
For example the following holds for all stateful session beans:
StatefulHome sfh = ...//get home interface for stateful bean
Stateful bean1 = sfh.create();
Stateful bean2 = sfh.create();
if (bean1.isIdentical(bean1)){} //this is true!
if (bean1.isIdentical(bean2)){} //this is false!
//Note that the second test would evaluate to true for stateless beans
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.
Advantages of EJB
Its very simple question to answer but its a experience to understand it. I will
try to answer : First of all, why session beans ? aren't they simple java
classes ? yes! they are ! But these are classes which are meant to be running in
ejb server environment. whenever a http request comes , your servlet will create
a objetc of the class and will use it and then it will be garbage collected.
while in ejb server environment , u dont control the life of these objects
rather server will create a pool before even first request comes and you are
simply assigned one of these and taken back after u r finished. so instantiation
and killing is avoided for each request.It saves a lot of processing and memory
which is critical for any enterprise application. secondly, entity beans are
answer to the persistance problem.You dont need to write embedded sql inside ur
java classes to access database.It is handled by container software. thirdly, u
dont need to haggle around with rmi problems , it is taken care of by ejb
server. most important of all, it supports 2-phase commit. you can have a
transaction spawned across multiple server connections and u dont need to code
for this functionality. with ejb 2.0 coming up , OR mapping and message beans
are introduced , so advantages are not countable.
Its oke that the server provides these services to EJB's. But these advantages
are more or less for the App server.What stops the App server from providing
these services to simple java classes. Do they(EJB) have any feature that at
runtime they become entitled for all these services or its up to the server to
provide these services.
Actually , if u look at the ejb interfaces that u have to implement to create
ejbs,
u will see that there are methods like ejbCreate(),
ejbPostCreate(), setEntityContext() etc.,
These methods are life cycle methods which are actually being called by ejb
server to manage your ejb java object. so ur ejb java classes are like any java class except that
these
are following a protocol that helps server to talk to them
and let them use many services that ejb server provides,
simply by telling it either in xml format or by some java class that provides
this information in specific format.these are called deployment discriptors.
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:
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.
In a few words, I would say that the main reason is because there is a clear division of roles and responsabilities between the two interfaces.
The home interface is your way to communicate with
the container, that is who is responsable of creating, locating even removing
one or more beans.
The remote interface is your link to the bean, that will allow you to
remotely access to all its methods and members.
As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.
what is a container?
Answer
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.
An enterprise bean depends on the container for everything it needs. If an enterprise bean needs to access a JDBC connection or another enterprise bean, it does so through the container; if an enterprise bean needs to access the identity of its caller, obtain a reference to itself, or access properties it does so through the container. The enterprise bean interacts with its container through one of three mechanisms: callback methods, the EJBContext interface, or JNDI.
Callback Methods: Every bean implements a subtype of the EnterpriseBean interface which defines several methods, called callback methods. Each callback method alerts the bean of a different event in its lifecycle and the container will invoke these methods to notify the bean when it's about to pool the bean, persist its state to the database, end a transaction, remove the bean from memory, etc. The callback methods give the bean a chance to do some housework immediately before or after some event. Callback methods are discussed in more detail in other sections.
EJBContext: Every bean obtains an EJBContext object, which is a reference directly to the container. The EJBContext interface provides methods for interacting with the container so that that bean can request information about its environment like the identity of its client, the status of a transaction, or to obtain remote references to itself.
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 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.
Diff bet servlet and java beans?
JavaBeans are a set of rules to follow to create reusable software components,
or beans. This contains properties and events. At the end you have a component
which could be examined by a program (like an IDE) to allow the user of your
JavaBean component to configure it and to run in its Java programs.
Servlets are Java classes running in a Servlet engine implementing a particular interface: Servlet, forcing you to implement some methods (service()). The servlet is an extension of your web server where this servlet is running on and only lets you know when a user requests a GET or POST calls from a web page to your servlet.
So, both have nothing in common except Java.
Diff bet serveltes and jsp?
Short answer: a
JSP is a Servlet that thinks it's a Web page.
Medium answer:
Both use server-side Java to dynamically generate web pages. The source code to
a JSP looks like HTML, with Java embedded inside funny tags (*); the source code
to a servlet looks like Java, with HTML embedded in out.print(...) statements.
Both use the Servlet API to communicate with the web server and the client. In
fact, a JSP gets compiled into a servlet, so they're almost identical in terms
of expressive power. The choice is, whether you're more comfortable coding your
pages in Java or in JSP-style HTML; and since you can call a JSP from a Servlet
and vice versa, you don't have to make an either-or decision.
Long answer: See
the
Servlet FAQ
and the
JSP FAQ for
all the information you need about both technologies.
(*) "Funny
tags:" JSP can contain (a) normal HTML tags, (b) JSP tags like <jsp:include>,
(c)
custom tags,
(d) scriptlets (Java code surrounded with <% and %>).
What is a
servlet engine?
A "servlet engine" is a program that plugs
in to a web server and runs servlets. The term is obsolete; the preferred term
now is "servlet container" since that applies both to plug-in engines and to
stand-alone web servers that support the Servlet API.
Difference between doGet and doPost ?
doGet is called in response to an HTTP
GET request. This happens when users click on a link, or enter a URL into the
browser's address bar. It also happens with some HTML FORMs (those with
METHOD="GET" specified in the FORM tag).
doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag).
Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions. You probably shouldn't override service().