INTRODUCTION
Various programming models were made public like procedural programming, modular programming and non procedural programming model.
Apart from these models reusable component programming model was introduced to put programmers at ease and to utilise the reusability as its best. Reusable Component model specifications were adopted by different vendors and they came with their own component model solutions.
JAVABEANS
Enterprise JavaBeans are software component models, their purpose is to build/support enterprise specific problems. EJB - is a reusable server-side software component.
Enterprise JavaBeans facilitates the development of distributed Java applications, providing an object-oriented transactional environment for building distributed, multi-tier enterprise components. An EJB is a remote object, which needs the services of an EJB container in order to execute.
EJBs have several benefits. First of all, they help bean developers write large applications with distributed components more easily. Recall that the EJB container provides system-level services to each bean deployed in a J2EE application server. This means bean developers do not have to handle complex issues such as transaction management, resource pooling, security, and multithreaded programming. Instead, they focus only on business logic in their bean methods.
EJBs also benefit clients in the presentation tier. Clients become thinner,since they implement only presentation logic and use EJBs for their business methods. EJBs are also portable components, which means you can build different enterprise applications with the same EJBs and run them on any J2EE application server
JAVABEAN CONCEPTS
Typical unifying features that distinguish a Bean are:
• Introspection: Builder tools discover a Bean’s features (ie its properties, methods, and events) by a process known as INTROSPECTION. Beans supports introspection in two ways:
1) Low Level Introspection (Reflection) + Intermediate Level Introspection (Design Pattern): Low Level Introspection is accomplished using java.lang.reflect package API. This API allows Java Objects to discover information about public fields, constructors, methods and events of loaded classes during program execution i.e., at Run-Time. Intermediate Level Introspection (Design Pattern) is accomplished using Design Patterns. Design Patterns are bean features naming conventions to which one has to adhere while writing code for Beans. java.beans.Introspector class examines Beans for these design patterns to discover Bean features. The Introspector class relies on the core reflection API. There are two types of methods namely, accessor methods and interface methods. Accessor methods are used on properties and are of two sub-types (namely getter methods and setters methods). Interface methods are often used to support event handling.
2) Higest Level or Explicit Introspection (BeanInfo): It is accomplished by explicitly providing property, method, and event information with a related Bean Information Class. A Bean information class implements the BeanInfo interface. A BeanInfo class explicitly lists those Bean features that are to be exposed to the application builder tools. The Introspector recognises BeanInfo classes by their name. The name of a BeanInfo class is the name of the bean class followed by BeanInfo word e.g., for a bean named “Gizmo” the BeanInfo name would be “GizmoBeanInfo”.
• Properties: Are a Bean’s appearance and behaviour characteristics that can be changed at design time.
• Customisation: Beans expose properties so they can be customised during the design time.
• Events: Enables Beans to communicate and connect to each other.
Beans can also be used just like any other Java class, manually (i.e., by hand programming), due to the basic Bean property, “Persistence”.
Following are the two ways:
• Simply instantiate the Bean class just like any other class.
• If you have a customised Bean (through some graphic tool) saved into a serialised file (say mybean.ser file), then use the following to create an instance of the Customised Bean class...
try {
Introduction to Java Beans
MyBean mybean = (MyBean) Beans.instantiate(null, "mybean");
} catch (Exception e) {
}
• Connecting Events: Beans, being primarily GUI components, generate and respond to events. The bean generating the event is referred to as event source and the bean listening for (and handling) the event is referred to as the event listener.
• Bean Properties: Bean properties can be categorised as follows...
- Simple Property are basic, independent, individual prperties like width, height, and colour.
- Indexed Property is a property that can take on an array of values.
- Bound Property is a property that alerts other objects when its value changes.
- Constrained Property differs from Bound Property in that it notifies other objects of an impending change. Constrained properties give the notified objects the power to veto a property change.
JavaBeans Syntax
The syntax of JavaBeans follows a set of conventions for writing reusable components in Java.
Here are the key syntax elements of JavaBeans:
Class Declaration:
-
JavaBeans are defined as regular Java classes.
-
The class should have a public access modifier.
-
The class should have a default (no-argument) constructor.
Private Fields:
-
The class should have private instance variables (fields) to encapsulate data.
-
The fields should follow the standard naming conventions, such as using camel case.
Public Getter and Setter Methods:
-
Each private field should have a corresponding public getter method to retrieve the value of the field.
-
Each private field should have a corresponding public setter method to set the value of the field.
-
Getter methods should follow the naming convention of "get()" or "is()" for boolean fields.
-
Setter methods should follow the naming convention of "set()".
Serializable Interface (Optional):
If the JavaBean needs to be serialized, it can implement the Serializable interface.
Event Handling (Optional):
If the JavaBean needs to support event handling, it can define additional methods or interfaces related to event registration, notification, and listeners.
Here's an example of the syntax for a simple JavaBean:
JavaBeans in Java
JavaBeans is a platform independent class that encapsulates several objects into a single one, known as the bean.
It is written in the Java programming language. JavaBeans allows us to access objects from various places and contains various elements, such as constructors, getter/setter, etc.
JavaBean class follows different conventions, which are listed below:
-
It must have a default constructor or no-arg constructor.
-
It must be Serializable, as it allows us to save, store, and restore the JavaBean state that we are working on.
-
It provides a getter method to read the values of a readable property and a setter method to update the value.
JavaBeans Class in Java
Explanation:
-
In this example, the Person class follows the JavaBeans conventions:
-
It has a public class declaration.
-
It has private instance variables (name and age) to encapsulate data.
-
It provides public getter and setter methods (getName(), setName(), getAge(), setAge()) for accessing and modifying the private fields.
-
It implements the Serializable interface, indicating that objects of this class can be serialized.
Benefits of Using Beans in Java
- JavaBean is mutable, which means it lacks the benefits of immutable objects.
- It will be in an inconsistent state partway through its construction.
- Creating setter and getter methods for every property may result in boilerplate code.
- Public in nature
- It must take some argument.
- Return-type must be void.
- It must be prefixed with the word ‘set’.
Access Beans in Java
To access JavaBeans, you can use the public getter and setter methods provided by the beans. The getter methods allow you to retrieve the values of the bean's properties, while the setter methods allow you to modify the property values.
Person person = new Person();
2. Use the getter methods to retrieve the values of the properties:
String name = person.getName();
3. Use the setter methods to modify the property values:
By calling the appropriate getter and setter methods, you can access and manipulate the properties of the JavaBean.
Example:
Here's a complete example showing how to access a Person JavaBean: In this example, we create an instance of the Person JavaBean, set the name and age properties using the setter methods, and then retrieve the values using the getter methods. Finally, we print the values to the console.
Life Cycle of Java Beans
The life cycle of a JavaBean refers to the different stages that a JavaBean instance goes through, from its creation to its destruction.
The life cycle of a JavaBean can be summarized in the following stages:
Destruction: At some point, the JavaBean may be destroyed, either explicitly or implicitly. Explicit destruction can be triggered by invoking a specific method, while implicit destruction occurs when the JavaBean goes out of scope or when the application or container shuts down. Destruction typically involves releasing resources, closing connections, and performing any necessary cleanup tasks.
BASIC EJB EXAMPLE
EJBs are distinguished along three main functional roles. Within each primary role, the EJBs are further distinguished according to subroles. By partitioning EJBs into roles, the programmer can develop an EJB according to a more focused programming model than, if, for instances such roles were not distinguished earlier. These roles also allow the EJB container to determine the best management of a particular EJB based on its programming model type.
There are three main types of beans:
· Session Beans
· Entity Beans
· Message-driven Beans
Session Beans
Session beans represent an interactive session with one or more clients. Session beans may maintain state, but only during the time a client interacts with the bean. This means session beans do not store their data in a database after a client terminates. Therefore, a session EJB is a non persistent object.
Its lifetime is the duration of a particular interaction between the client and the EJB. The client normally creates an EJB, calls methods on it, and then removes it. If, the client fails to remove it, the EJB container will remove it after a certain period of inactivity. There are two types of session beans:
· Stateless Session Beans: A stateless session EJB is shared between a number of clients. It does not maintain conversational state.The values of any object’s instance variables (fields) define the state of an object. Usually, method calls change an object’s state. A stateless session bean, however, does not keep track of client-specific data. In fact, no instance variable in a stateless session bean stores client-specific data. This unique property allows the EJB container to create a pool of instances, all from the same stateless session bean.The algorithm for creating new instance or instance reuse is container specific.
Why is this important?
When a client invokes a method of a stateless session bean, the EJB container fetches an instance from the pool. Any instance will do, since the bean does not store any client-specific information. As soon as the method finishes executing, the instance is available for another client’s request. This arrangement makes stateless session beans highly scalable for a large number of clients (a small number of instances can service many clients). It also means better performance. The EJB container does not have to move stateless session beans from memory to secondary storage to free up resources—it simply regains memory and other resources by destroying the instances.
All enterprise beans have different states that they go through during their lifetimes. The life cycle of a bean is managed by the EJB container. Figure 1 shows the life cycle for a stateless session bean.
There are only two states in a stateless session bean: a Does Not Exist state and a Ready state.
After the container creates an instance of a stateless session bean with Class.newInstance(), the container invokes the setSessionContext() and ejbCreate() methods in the bean. This makes the bean transitionto the Ready state. The bean developer uses the setSessionContext() method to access the bean’s context from the container. The container invokes the ejbCreate() method to initialize the bean and access resources. Once the bean is in the Ready state, a client may call its business methods. The container calls the bean’s ejbRemove() method when it no longer requires a bean instance. This makes the bean return to the Does Not Exist state.
When should you use stateless session beans?
Stateless session beans are appropriate when a task is not tied to a specific client. You could, for instance, use a stateless session bean to send an e-mail confirmation or calculate interest payments for loan applications. You could also use a stateless session bean to read data from a database. Such a bean would be useful for generating reports or viewing a collection of items.
Life Cycle of a Stateless Session Bean
The Figure 1 shows the life cycle of a Stateless Session Bean.
• Does not exist: In this state, the bean instance simply does not exist.• Ready state: When EJB Server is first started, several bean instances are created and placed in the Ready pool. More instances might be created by the container as and when needed by the EJBcontainer.
· Stateful Session Beans: A stateful session bean is a bean that is designed to service business processes that span multiple method requests or transaction. To do this, the stateful bean retains the state for an individual client. If, the stateful bean’s state is changed during method invocation, then, that same state will be available to the same client upon invocation.
In a stateful session bean, the instance variables store client-specific data. Each stateful session bean, therefore, stores the conversational state of one client that interacts with the bean. This conversational state is maintained by the bean while clients call its business methods. The conversational state is not saved when the client terminates the session. The EJB container manages stateful session beans differently from stateless beans. Note that with stateful session beans, it’s not possible for the container to create a pool of instances and share them among multiple clients. Since a stateful session bean stores client-specific data, the container creates a separate bean instance for each client. So that conversational state is not lost, the container saves and restores stateful session beans when moving them between memory and secondary storage. All this means that stateful session beans have more overhead associated with them and are not as scalable as stateless session beans.
The life cycle of a stateful session bean is also more involved, as Figure 2 shows. Stateful session beans have three states: a Does Not Exist state, a Ready state, and a Passive state.
When a client calls create(), the EJB container instantiates the bean with Class.newInstance() and calls its setSessionContext() and ejbCreate() methods. This makes the bean transition to the Ready state where it can accept calls to its business methods. When the client terminates a session, the container calls the ejbRemove() method in the bean. The bean returns to the Does Not Exist state where it is marked for garbage collection.A stateful session bean transitions to the Passive state when the container passivates the bean; i.e., the container moves the bean from memory to secondary storage. The container calls the bean’s ejbPassivate() method just before passivating a bean. If the bean is in the Passive state when a client calls one of its business methods, the container activates the bean. The container restores the bean in memory before calling the bean’s ejbActivate() method. This makes the bean return to the Ready state.
When should you use stateful session beans? In general, any situation where a bean must remember client information between method invocations is a candidate for stateful session beans. A good example on the web is a virtual shopping cart in an online store. When clients log on to the system, a stateful session bean can maintain the items in the shopping cart. Each client has its own instance of a stateful session bean, which maintains a separate shopping cart for each client. Note that with stateful session beans, client-specific information is stored in memory, not to a database. Therefore, you should use stateful session beans in situations where losing session data is not a problem when a client terminates a session. In our hypothetical online store, for instance, we discard the virtual shopping cart if a client decides not to buy the items. Saving the shopping cart contents comes under the application and use of entity beans.
Life Cycle of a Stateful Session Bean:
The Figure 2 shows the life cycle of a Stateful Session Bean.
• Does not exist: In this state, the bean instance simply does not exist.• Ready state: A bean instance in the ready state is tied to a particular client and engaged in a conversation.• Passive state: A bean instance in the passive state is passivated to conserve resources.
setSessionContext(SessionContext ctx) :Associate your bean with a session context.
Your bean can make a query to the context about its current transactional state, and its current security
state.
ejbCreate( …) : Initialise your session bean. You would need to define several ejbCreate (…) methods and then, each method can take up different arguments. There should be at least one ejbCreate() in a session bean.
ejbPassivate(): This method is called for, just before the session bean is passivated and releases any resource that bean might be holding.
ejbActivate(): This method is called just for, before the session bean is activated and acquires the resources that it requires.
ejbRemove(): This method is called for, by the ejb container just before the session bean is removed from the memory. The use of a Session Bean
In general, one 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 and therefore.• The bean implements a web service.
Stateful session beans are appropriate if, any of the following conditions are true:• 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.
To improve performance, one 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 a promotional email to several registered users.
The use of a Session Bean
Singleton Session Beans
A singleton session bean maintains one instance per
application and the instance exists for the lifecycle of the
application. It offers the same functionality as the stateless session
beans. But the only difference is that there is only one singleton
session bean per application while in the stateless session bean a pool
of beans is used.
From that pool, any of the session beans may respond to the client.
We can implement it in the web-service endpoints. It takes care of the
state but does not hold the state if unexpected crashes or shutdown
occur. It can be used if we want to perform cleanup tasks on closing the
application or shut down as well. It is because it operates throughout
the life cycle of the application.
Singleton session beans are suitable for the following conditions:
- The state of the bean must be shared across the application.
- A single enterprise bean should be accessed by multiple threads concurrently.
- The application needs an enterprise bean to perform undertakings upon application startup and shutdown.
- The bean implements a web service.
Entity Beans:
Entity beans are in-memory business objects that correspond to data in persistent storage. An entity bean typically corresponds to a row in a relational database. The bean’s instance variables represent data in the columns of the database table. The container must synchronize a bean’s instance variables with the database. Entity beans differ from session beans in that instance variables are stored persistently. Entity beans also have primary keys for identification and may have relationships with other entity beans. Another key concept is that clients may share entity beans.
The EJB container locates an entity bean by its primary key. Primary keys are unique identifiers. Database software prevents you from inserting new data if the primary key is not unique. If multiple clients attempt to access the same data in an entity bean, the container handles the transaction for you. Through an entity bean’s deployment descriptor, the developer specifies the transaction’s attributes associated with entity bean methods. The container performs the necessary rollbacks if any step in the transaction fails. This is one of the most vital services that the container provides for entity bean developers.
An entity bean life cycle has three states: Does Not Exist, Pooled, and Ready.
Life Cycle of an Entity
Bean
Figure 3 shows the life cycle diagram.An entity bean has the following
three states:
- Does not exist: In
this state, the bean instance
simply does not exist.
- Pooled state: When the EJB server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to a particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set.
- Ready state: A bean instance in the ready state is tied to a particular data, that is, it represents an instance of an actual business object.
To transition from the Does Not Exist state to the Pooled state, the container creates a bean instance with Class.newInstance() and calls the setEntityContext() method in the bean. This allows bean developers to access a bean’s context from the argument passed to setEntityContext(). In the Pooled State, all entity bean instances are identical.
Note that there are two paths for an entity bean to transition from the Pooled state to the Ready state. The client can invoke the entity bean’s create() method and consequently insert new data into the underlying database. The client can alternatively invoke one of the bean’s “finder” methods. This performs a select query on the underlying database, synchronizing the bean’s persistent fields from the data already in the database. If a client wants to insert data into the database, the client calls the create() method with arguments representing the data values. This makes the container call ejbCreate() to initialize the bean before calling ejbPostCreate(). In the Ready state, clients may invoke business methods in the entity bean.
If, on the other hand, a client reads data from the database, the client calls the findByPrimaryKey() method or another finder method. This makes the container deliver an entity bean instance directly to the client if its state is Ready. If the requested bean is in the Pooled state, the container activates the bean and calls the bean’s ejbActivate() method. This changes the bean’s state to Ready.
There are also two paths from the Ready state to the Pooled state. If a client wants to remove data from the database, the client calls remove(). This makes the container call the bean’s ejbRemove() method. If the container needs to reclaim resources used by an entity bean, it can passivate the bean. To passivate an entity bean, the container calls ejbPassivate(). Both calls change the bean’s state from Ready to Pooled.
At the end of the life cycle, the container removes the bean instance from the pool and calls the bean’s unsetEntityContext() method. This changes the bean’s state from Pooled to Does Not Exist.
When should you use entity beans? An entity bean is appropriate for any situation where data must be maintained (created, updated, selected, deleted) in persistent storage. Entity beans should represent business data rather than perform a task-related function.
Entity beans have two types of persistence: Bean-Managed Persistence (BMP) and Container-Managed Persistence (CMP).
·
Bean-managed
persistence (BMP): The entity bean’s implementation manages persistence by coding database
access and updating
statements in callback
methods.
Entity beans with bean-managed persistence contain code that accesses a database. The beans’ code contains SQL calls to read and write to the database. BMP gives developers more control over how an entity bean interacts with a database. An entity bean with BMP can implement SQL code targeted for a specific database platform or it can use a Data Access Object (DAO) to hide the details of a particular database. A DAO encapsulates database operations into helper classes for a specific database. DAOs make entity beans with BMP more portable, although the bean developer still has to manipulate database access with Java methods and classes
- Container-managed persistence (CMP): The container uses specifications made in
the deployment descriptor to perform database access and update statements automatically.
Entity beans with container-managed persistence do not contain code for database access. The container generates the necessary database calls for you. This
approach makes CMP entity beans more portable than BMP entity beans with
DAOs. With the deployment descriptor set to specific attributes for CMP
behavior, entity bean developers are spared from having to write SQL code for
database access.
Entity Relationships
Entity beans, regardless of whether they use BMP or CMP for database access, can have relationships with other entity beans according to an abstract persistence schema. An entity bean’s abstract schema defines a bean’s persistent fields and its relationships with other entity beans. The persistent fields of anentity bean are stored in a database. A bean’s relationship to another bean is stored as a relationship field. Relationship fields must also be stored in the database. With BMP, the developer decides how relationship fields are represented in the underlying database (using foreign keys allows data in one table to relate to data in another table). With CMP, the container constructs the appropriate cross-reference tables based on the abstract schema description the bean developer provides.
Required Methods in Entity Bean:
Entity beans can be bean managed or container managed. Here, are the methods that are required for entity beans :
setEntityContext():This method is called for, if a container wants to increase its pool size of bean instances, then, it will instantiate a new entity bean instance. This method associates a bean with context information. Once this method is called for, then, the bean can access the information about its environment.
ejbFind(..):This method is also known as the Finder method. The Finder method locates one or more existing entity bean data instances in underlying persistent store.
ejbHome(..):The Home methods are special business methods because they are called from a bean in the pool before the bean is associated with any specific data. The client calls for, home methods from home interface or local home interface.
ejbCreate():This method is responsible for creating a new database data and for initialising the bean.
ejbPostCreate():There must be one ejbPostCreate() for each ejbCreate(). Each method must accept the same parameters. The container calls for, ejbPostCreate() right after ejbCreate().
ejbActivate():When a client calls for, a business method on a EJB object but no entity bean instance is bound to EJB object, the container needs to take a bean from the pool and transition into a ready state. This is called Activation. Upon activation the ejbActivate() method is called for by the ejb container.
ejbLoad():This method is called for, to load the database in the bean instance.
ejbStore():This method is used for, to update the database with new values from the memory. This method is also called for during ejbPassivate().
ejbPassivate():This method is called for, by the EJB container when an entity bean is moved from the ready state to the pool state.
ejbRemove():This method is used to destroy the database data. It does not remove the object. The object is moved to the pool state for reuse.
unsetEntityContext():This method removes the bean from its environment. This is called for, just before destroying the entity bean.
The Use of the Entity Bean:
Use an entity bean under the following conditions:• The bean represents a business entity and not a procedure. For example, BookInfoBean would be an entity bean, but BookInfoVerifierBean would be a session bean.
• The bean’s state must be persistent. If the bean instance terminates or if the Application Server is shut down, the bean's state still exists in persistent storage (a database).Message-Driven Beans
A Message-driven beans allow J2EE applications to receive messages asynchronously. This means a client’s thread does not block while waiting for an EJB’s business method to complete. Instead of calling a business method directly in a bean, clients send messages to a server that stores them and returns control to the client right away. The EJB container has a pool of message bean instances that it uses to process messages. When the message is received, the message bean can access a database or call an EJB business method. This arrangement allows the invocation of lengthy business methods without making the client wait for the method to complete its job. Clients interact with these EJBs by sending messages to the queues or topics to which they are listening. Although a message-driven EJB cannot be called for, directly by clients, it can call other EJBs itself.
Using JMS
Message beans use the Java Message Service (JMS) to handle messaging. Figure 4 shows the approach.
Figure 4 Message-Driven Bean, JMS, and EJB Container Architecture
Clients use a JMS server to store messages in aqueue or topic destination. In JMS, a topic is used for a one-to-many broadcast and a queue for a one-to-one communication. When a message arrives, the container calls the onMessage() method in the message bean to process the message. Using the JMS server as an intermediary decouples the client from the message bean. This is a key point with message beans. The container uses a bean instance from a pool of message beans. The container also handles all the details of registering a message bean as a listener for queue or topic messages.
Another key point with message beans is that they are stateless. This makes message beans highly scalable, like stateless session beans. A message bean retains no conversational state and can handle messages from multiple clients. Message beans can connect to databases and call methods in other EJBs, too. This makes message beans a valuable component in enterprise designs that require asynchronous processing from clients.
Message beans also have a simple life cycle, as shown in Figure 5. There are only two states: Does Not Exist and Ready.
To change from the Does Not Exist state to the Ready state, the container instantiates the message bean with Class.newInstance() and calls its setMessageDrivenContext() and ejbCreate() methods.
In the Ready state, a message bean may receive messages from the JMS server. When a message arrives, the container calls the onMessage() method in the message bean and passes the message to the method as an argument. Note that message processing does not make a message bean change state.
Figure 5 Message Bean Life Cycle Like stateless session beans, the container never passivates a message bean
because message beans do not contain client-specific data. The life cycle of a
message bean ends when the container calls the ejbRemove() method. This
makes the message bean’s state change back to the Does Not Exist state.
When should you use message beans? In general, message beans are useful
for receiving messages asynchronously (no waiting). You should consider
using a message bean to decouple a client who cannot tolerate waiting for a
lengthy business method to complete. A message bean that sends an e-mail
confirmation to a large group of recipients is a good example.
The J2EE application server uses JMS to implement message-driven beans.
A message bean is relatively easy to implement, since the container does most
of the setup work that JMS requires. Clients and Interfaces
A well-designed interface is important in enterprise programming because it
represents the client’s view of an enterprise bean. Clients invoke business
methods in a session bean or an entity bean only through a bean’s interface.
This approach allows the EJB container to intercept client calls made through
the EJB interface. The container can then perform any required system processing (such as transaction management) before forwarding the call to the method
inside the EJB implementation class. Two types of interfaces are possible with session and entity beans. Let’s find
out what they are and how you might use them. (Note that message-driven
beans do not have client interfaces since access is only through the JMS server. Home and Remote Interfaces
Clients may access session and entity beans remotely (from a machine running
a different JVM) or locally (within the same JVM). For remote access, session
and entity beans have a remote interface and a home interface. These interfaces
represent the client’s view of an enterprise bean. The remote interface defines a
bean’s business methods and the home interface defines life cycle methods.
The home interface also defines finder and home methods for entity beans. Figure 6 shows the home and remote interfaces for a Customer EJB entity
bean that has remote access.
Remote clients can be web components, J2EE application clients, or other
enterprise beans. Remote clients may execute on one machine, and the enterprise bean it uses may run on a different machine. You must create both a
remote interface and a home interface for a client to have remote access to the
bean.
A singleton session bean maintains one instance per application and the instance exists for the lifecycle of the application. It offers the same functionality as the stateless session beans. But the only difference is that there is only one singleton session bean per application while in the stateless session bean a pool of beans is used.
From that pool, any of the session beans may respond to the client. We can implement it in the web-service endpoints. It takes care of the state but does not hold the state if unexpected crashes or shutdown occur. It can be used if we want to perform cleanup tasks on closing the application or shut down as well. It is because it operates throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:
- The state of the bean must be shared across the application.
- A single enterprise bean should be accessed by multiple threads concurrently.
- The application needs an enterprise bean to perform undertakings upon application startup and shutdown.
- The bean implements a web service.
Entity Beans:
Life Cycle of an Entity Bean
- Does not exist: In
this state, the bean instance
simply does not exist.
- Pooled state: When the EJB server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to a particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set.
- Ready state: A bean instance in the ready state is tied to a particular data, that is, it represents an instance of an actual business object.
- Container-managed persistence (CMP): The container uses specifications made in the deployment descriptor to perform database access and update statements automatically.
The Use of the Entity Bean:
Message-Driven Beans
A Message-driven beans allow J2EE applications to receive messages asynchronously. This means a client’s thread does not block while waiting for an EJB’s business method to complete. Instead of calling a business method directly in a bean, clients send messages to a server that stores them and returns control to the client right away. The EJB container has a pool of message bean instances that it uses to process messages. When the message is received, the message bean can access a database or call an EJB business method. This arrangement allows the invocation of lengthy business methods without making the client wait for the method to complete its job. Clients interact with these EJBs by sending messages to the queues or topics to which they are listening. Although a message-driven EJB cannot be called for, directly by clients, it can call other EJBs itself.
Using JMS
Message beans use the Java Message Service (JMS) to handle messaging. Figure 4 shows the approach.
Figure 4 Message-Driven Bean, JMS, and EJB Container ArchitectureClients use a JMS server to store messages in aqueue or topic destination. In JMS, a topic is used for a one-to-many broadcast and a queue for a one-to-one communication. When a message arrives, the container calls the onMessage() method in the message bean to process the message. Using the JMS server as an intermediary decouples the client from the message bean. This is a key point with message beans.
The container uses a bean instance from a pool of message beans. The container also handles all the details of registering a message bean as a listener for queue or topic messages.
Another key point with message beans is that they are stateless. This makes message beans highly scalable, like stateless session beans. A message bean retains no conversational state and can handle messages from multiple clients. Message beans can connect to databases and call methods in other EJBs, too. This makes message beans a valuable component in enterprise designs that require asynchronous processing from clients.
Message beans also have a simple life cycle, as shown in Figure 5. There are only two states: Does Not Exist and Ready.
To change from the Does Not Exist state to the Ready state, the container instantiates the message bean with Class.newInstance() and calls its setMessageDrivenContext() and ejbCreate() methods.
In the Ready state, a message bean may receive messages from the JMS server. When a message arrives, the container calls the onMessage() method in the message bean and passes the message to the method as an argument. Note that message processing does not make a message bean change state.
Figure 6 Interfaces for Remote Access
Local Home and Local Interface
Clients may also interact with session or entity beans locally. This means a local
client executes on the same machine as the enterprise bean it uses. Local clients
can be web components or other enterprise beans, but not J2EE client applications. A common use of local interfaces is among related entity beans (entity
beans with relationship fields to other entity beans). Also, you can construct a
business process session bean as a front end (a session facade) to one or more
entity beans.
To have local access, you must create a local interface with business
methods and a local home interface with life cycle and finder methods. A local
interface is also the only way to have entity beans communicate with other
entity beans in container-managed relationships. In an abstract schema, any
entity bean that is the target of a container-managed relationship field must
have a local interface.
The primary reason for using local interfaces is increased performance. With
local access to session or entity beans, method calls execute faster than remote
calls, since both client and bean execute under control of the same EJB container.
Figure 7 shows the local home and local interfaces for
a Customer EJB entity bean with local access.
Key Point Summary
Here
are the key points from this chapter.
• The J2EE platform gives you a multi-tiered
application model to develop distributed components.
• A three-tier architecture places web
components and business components in the middle tier. The presentation tier
contains client applications and the database tier contains database programs.
• The J2EE components consist of technologies
like enterprise beans, servlets, and JSP. They also contain APIs that are
valuable to EJBs, such as JNDI, JDBC, and JMS.
• Remote Method Invocation (RMI) provides
support for network calls used by enterprise beans in the J2EE architecture.
• The J2EE application server has containers
that provide services to enterprise beans and web components.
• A deployment descriptor is an XML file that
describes how the container will configure an EJB to run on a J2EE application
server.
•
The containers in the J2EE architecture manage many services, such as EJB and
servlet life cycles, database connection pooling, security, transaction
management, and data persistence.
•
Enterprise beans are server-side components that encapsulate business logic and
business data.
•
The EJB container provides system-level services to each bean deployed in a
J2EE application server. These services include transaction management,
resource pooling, security, and multithreading control.
• There are three types of enterprise beans:
session beans, entity beans, and message-driven beans. Session beans may be stateless
or stateful, and entity beans may use bean-managed persistence or
container-managed persistence. • Stateless session beans do not store
client-specific data in their instance variables. Stateless session beans are
scalable and can be shared by many clients.
•
Stateful session beans do store client-specific data in their instance
variables. Stateless session beans store the conversational state between a
client and a bean. The EJB container may passivate or activate stateful session
beans by moving the bean between memory and secondary storage.
• Stateless session beans are appropriate for
general tasks that do not apply to a specific client. Stateful session beans
apply to situations where a bean must remember nonpersistent client information
between method invocations.
•
Entity beans are in-memory business objects that correspond to data in persistent
storage.
• Entity beans with bean-managed persistence
contain SQL calls to read and write to a database.
•
Entity beans with container-managed persistence do not contain code for
database access. The container generates the necessary database calls for you.
•
An entity bean’s abstract schema defines a bean’s persistent fields and its
relationships with other entity beans.
•
A bean’s relationship to another bean is stored as a relationship field. The
container uses relationship fields to identify related beans.
•
Message beans allow J2EE applications to receive messages asynchronously.
Message beans use the Java Message Service (JMS) to handle messaging.
•
Message beans are highly scalable, similar to stateless session beans.
•
The home or local home interface of an enterprise bean defines life cycle
methods. The local or remote interface contains the business methods.
•
Local interfaces allow enterprise beans to call methods locally, which performs
better than remote calls across a network.
Additional
Resources
- Books:
- "Java: The Complete Reference" by
Herbert Schildt
- "Effective Java" by Joshua Bloch
- "Enterrprise Javabeans Overview "
- Online
Courses:
- Coursera - Java Programming and Software
Engineering Fundamentals
- Video
Tutorials:
- Java Tutorial for Beginners by Programming with
Mosh
- Java Programming Tutorial - Full Course for
Beginners by CodeWithChris
- Websites:
- Oracle Java Documentation
- GeeksforGeeks - Java Programming Language
Figure 6 Interfaces for Remote Access
Local Home and Local Interface
Clients may also interact with session or entity beans locally. This means a local client executes on the same machine as the enterprise bean it uses. Local clients can be web components or other enterprise beans, but not J2EE client applications. A common use of local interfaces is among related entity beans (entity beans with relationship fields to other entity beans). Also, you can construct a business process session bean as a front end (a session facade) to one or more entity beans.
To have local access, you must create a local interface with business methods and a local home interface with life cycle and finder methods. A local interface is also the only way to have entity beans communicate with other entity beans in container-managed relationships. In an abstract schema, any entity bean that is the target of a container-managed relationship field must have a local interface.
The primary reason for using local interfaces is increased performance. With local access to session or entity beans, method calls execute faster than remote calls, since both client and bean execute under control of the same EJB container.
Figure 7 shows the local home and local interfaces for a Customer EJB entity bean with local access.
Key Point Summary
Here are the key points from this chapter.
• The J2EE platform gives you a multi-tiered application model to develop distributed components.
• A three-tier architecture places web components and business components in the middle tier. The presentation tier contains client applications and the database tier contains database programs.
• The J2EE components consist of technologies like enterprise beans, servlets, and JSP. They also contain APIs that are valuable to EJBs, such as JNDI, JDBC, and JMS.
• Remote Method Invocation (RMI) provides support for network calls used by enterprise beans in the J2EE architecture.
• The J2EE application server has containers that provide services to enterprise beans and web components.
• A deployment descriptor is an XML file that describes how the container will configure an EJB to run on a J2EE application server.
• The containers in the J2EE architecture manage many services, such as EJB and servlet life cycles, database connection pooling, security, transaction management, and data persistence.
• Enterprise beans are server-side components that encapsulate business logic and business data.
• The EJB container provides system-level services to each bean deployed in a J2EE application server. These services include transaction management, resource pooling, security, and multithreading control.
• There are three types of enterprise beans: session beans, entity beans, and message-driven beans. Session beans may be stateless or stateful, and entity beans may use bean-managed persistence or container-managed persistence. • Stateless session beans do not store client-specific data in their instance variables. Stateless session beans are scalable and can be shared by many clients.
• Stateful session beans do store client-specific data in their instance variables. Stateless session beans store the conversational state between a client and a bean. The EJB container may passivate or activate stateful session beans by moving the bean between memory and secondary storage.
• Stateless session beans are appropriate for general tasks that do not apply to a specific client. Stateful session beans apply to situations where a bean must remember nonpersistent client information between method invocations.
• Entity beans are in-memory business objects that correspond to data in persistent storage.
• Entity beans with bean-managed persistence contain SQL calls to read and write to a database.
• Entity beans with container-managed persistence do not contain code for database access. The container generates the necessary database calls for you.
• An entity bean’s abstract schema defines a bean’s persistent fields and its relationships with other entity beans.
• A bean’s relationship to another bean is stored as a relationship field. The container uses relationship fields to identify related beans.
• Message beans allow J2EE applications to receive messages asynchronously. Message beans use the Java Message Service (JMS) to handle messaging.
• Message beans are highly scalable, similar to stateless session beans.
• The home or local home interface of an enterprise bean defines life cycle methods. The local or remote interface contains the business methods.
• Local interfaces allow enterprise beans to call methods locally, which performs better than remote calls across a network.
Additional
Resources
- Books:
- "Java: The Complete Reference" by
Herbert Schildt
- "Effective Java" by Joshua Bloch
- "Enterrprise Javabeans Overview "
- Online
Courses:
- Coursera - Java Programming and Software
Engineering Fundamentals
- Video
Tutorials:
- Java Tutorial for Beginners by Programming with
Mosh
- Java Programming Tutorial - Full Course for
Beginners by CodeWithChris
- Websites:
- Oracle Java Documentation
- GeeksforGeeks - Java Programming Language
No comments:
Post a Comment