[Go to site: main page, start]

0% found this document useful (0 votes)
2 views13 pages

Creating A JavaBean (Advanced Java)

A JavaBean is a reusable software component in Java that follows specific conventions, including having a no-arg constructor and providing getter and setter methods for its properties. JavaBeans can be categorized into three types of Enterprise Java Beans (EJB): Session Beans, Entity Beans, and Message-Driven Beans, each serving different purposes in business applications. While JavaBeans offer advantages like reusability and easy maintenance, they also have disadvantages such as mutability and boilerplate code requirements.

Uploaded by

sekhon85578
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Creating A JavaBean (Advanced Java)

A JavaBean is a reusable software component in Java that follows specific conventions, including having a no-arg constructor and providing getter and setter methods for its properties. JavaBeans can be categorized into three types of Enterprise Java Beans (EJB): Session Beans, Entity Beans, and Message-Driven Beans, each serving different purposes in business applications. While JavaBeans offer advantages like reusability and easy maintenance, they also have disadvantages such as mutability and boilerplate code requirements.

Uploaded by

sekhon85578
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Creating a JavaBean

JavaBean
A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as getter
and setter methods.

Why use JavaBean?


According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class


1. //[Link]
2.
3. package mypack;
4. public class Employee implements [Link]{
5. private int id;
6. private String name;
7. public Employee(){}
8. public void setId(int id){[Link]=id;}
9. public int getId(){return id;}
10. public void setName(String name){[Link]=name;}
11. public String getName(){return name;}
12. }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.

1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. [Link]("Arjun");//setting value to the object
6. [Link]([Link]());
7. }}
8.
Note: There are two ways to provide values to the object. One way is by constructor
and second is by setter method.

JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean
The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.

Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to the
boilerplate code.
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It
encapsulates the business logic of an application. It is a specification for developing a
distributed business application on the Java platform. There are three types of
EJBs: Session Bean, Entity Bean, and Message-Driven Bean. In this section, we will
discuss all types of EJB in detail.

Let's discuss one by one in detail.

Session Bean
The bean sprout business idea that can be systematically used by customer, remote,
and web service. When a client wants to use an application distributed on a server,
then the client uses session bean methods. This session bean provides services to
customers, protecting them from complex problems by performing business
operations within the server.

To get to an application that is conveyed to the worker, the client summons the
meeting bean's strategies. The meeting bean performs work for its client, safeguarding
it from intricacy by executing business errands inside the worker. Remember that
session beans are not persistence.

There are two types of session beans:

o Stateless Session Beans


o Stateful Session Beans
o Singleton Session Beans

Stateless Session Beans


A stateless session bean doesn't keep a conversational state with the customer or
client. When a client invokes the methods for a stateless bean, the bean's instance
variable may contain a state explicitly to that client however only for the span of the
invocation.

At the point when the method has finished, the client explicit state should not be held.
However, the client may change the state of instance variable presented in pooled
stateless beans, and this state is held over to the following invocation of the pooled
stateless bean.

Besides this, during the invocation of the method, all instances of a stateless bean are
the same, permitting the EJB container to assign an instance to any client. Therefore,
the state of a stateless session bean should apply across all clients. It can be
implemented in a web-services.
Since they can maintain various customers, stateless session beans can offer better
adaptability for applications that require large numbers of clients. Ordinarily, an
application requires fewer stateless session beans than stateful session beans to
support the same number of clients.

To improve execution, we may choose a stateless session bean in the event that it has
any of these characteristics.

o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
o The bean implements a web service.

Stateful Session Beans


A stateful session bean is the same as an interactive session. The state of an object
comprises the values of its instance variables. In a stateful session bean, the instance
variables denote the state of a unique client/bean session. Since, the client interacts
with its bean. The state is usually called the conversational state. It maintains the state
of a client across multiple requests. So, we cannot implement it in the web services
because it cannot be shared. When the client terminates the session, it is no longer
associated with the client.

The state is held for the span of the client/bean session. In case if the client eliminates
the bean, the session closes and the state is omitted. This transient nature of the state
isn't an issue, because the interaction between the client and the beans ends. So, it is
not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:

o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise beans.

Note: Stateless and stateful both session beans are not persistent.
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:


o The state of the bean must be shared across the application.
o A single enterprise bean should be accessed by multiple threads concurrently.
o The application needs an enterprise bean to perform undertakings upon application
startup and shutdown.
o The bean implements a web service.

Entity Bean
An entity bean is an unpredictable business substance. It models a business substance
or models different activities inside a business interaction. It is used to encourage
business benefits that include data and calculations on that data. It can deal with
various, needy, diligent articles in playing out its essential assignments. A substance
bean is a far-off object that oversees steady information and performs complex
business rationale. It can be extraordinarily distinguished by an essential key.

It is a far-off object that oversees steady information, performs complex business


rationale, possibly utilizes a few ward Java protests, and can be remarkably
distinguished by an essential key. It ordinarily coarse-grained determined items since
they use steady information put away inside a few fine-grained relentless Java objects.
Element beans are diligent on the grounds that they do endure a worker crash or an
organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it
comprises a unique identity that can be fetched if we have a primary key. The type for
the unique key is defined by the bean provider. A client can retrieve the entity bean if
the primary has been misplaced. If the bean is not available, the EJB container first,
instantiates the bean and then re-populates the data for the client.
The diligence for entity bean information is given both to saving state when the bean
is passivated and for improving the state when a failover has detected. It can endure
in light of the fact that the information is put away determinedly by the holder in some
type of information stockpiling framework, like a data set.

Entity beans persist business data by using the following two methods:

o Bean-Managed Persistence (BMP)


o Container-Managed Persistence (CMP)

Bean Managed Persistence


Bean-managed persistence is more complicated in comparison to container-managed
persistence. Because it allows us to write the persistence logic into the bean class,
explicitly. In order to write the persistence handling code into the bean class, we must
know the type of database that is being used and how fields of the bean class are
mapped to the database. Therefore, it provides more flexibility between the database
and the bean instance.

It can be used as an alternative to CMP. If the deployment tools are incompatible for
mapping the bean instance's state to the database. The disadvantage of BMP is that
more work is required to define the bean and it ties the bean to a specific database
type and structure.

Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly
handles the relationship between the bean and the database. Bean developers focus
on the data and the business process. The principal constraint is that the EJB
compartment can most likely not produce information base access articulations with
the proficiency of a programmer.

Unlike BMP, CMP does not allow us to write database access calls in the methods of
the entity bean class. It is because the persistence is handled by the container at run-
time. The following two things are required to support the CMP:

o Mapping: It denotes that how to map an entity bean to a resource.


o Runtime Environment: A CMP runtime environment that uses the mapping
information to perform persistence operations on each bean.
Note: Entity bean has been replaced with Java persistence API.
Message-Driven Bean (MDB)
MDB is a Java Messaging Service (message listener). It consumes messages from a
queue or subscription of a topic. It provides an easy way to create or implement
asynchronous communication using a JMS message listener. An advantage of using
MDB is that it allows us to use the asynchronous nature of a JMS listener. We can
implement message-driven beans with Oracle JMS (Java Messaging Service).

There is an EJB container (contains MDBs pool) that handles the JMS queue and topic.
Each incoming message is handled by a bean that is invoked by the container. Note
that no object invokes an MDB directly. All invocation for MDB originates from the
container. When the container invokes the MDB, it can invoke other EJBs or Java
objects to continue the request.

It is quite similar to stateless session bean. Because it does not save informal state, also
used to handle multiple incoming requests. EJB has the following benefits over the
JMS are as follows:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.
o MDB is registered with the consumer. It means that at deployment time
QueueReceiver, TopicSubscriber, and its factory are registered by the container.
o The message ACK mode is specified.

The primary function of MDB is to read (receive) or write (send) incoming from a JMS
destination (i.e. queue or topic). While using MDB ensure that it is configured and
installed properly. It interacts with JMS and the JMS installed on the Oracle database.
The database retains queue or topic. The following figure depicts how MDB interacts
with the JMS destination.

The working of MDB is as follows:

o MDB creates and opens a JMS connection to the database by using the data source
(JMS resource provider). The JDBC driver is used to facilitate the JMS connection.
o A JMS session over the JMS connection is opened by the MDB.
o If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the
message for the MDB.

Note that it does not handle the requests that are requested by the clients instead it
handles requests that are placed into a queue.
MDB implements the [Link] interface and inherits the
[Link] class that provides the following methods:

Method Description

onMessage(msg) The container dequeues a message from the JMS queue


associated with this MDB and gives it to this instance by invoking
this method. This method must have an implementation for
handling the message appropriately.

setMessageDrivenContext(ctx) After the bean is created, the setMessageDrivenContext method


is invoked. This method is similar to the EJB setSessionContext and
setEntityContext methods.

ejbCreate() This method is used just like the stateless session bean ejbCreate
method. No initialization should be done in this method. However,
any resources that you allocate within this method will exist for
this object.

ejbRemove() Delete any resources allocated within the ejbCreate method.

Difference Between Session and Entity Bean


The following table depicts the key differences between session bean and entity bean.

Basis of Session Bean Entity Bean


Comparison

Primary Key It has no primary key. It is used to It has a primary key that allows us to find
identify and retrieve specific bean instances and can be shared by more than
instances. one client.

Stateless/ It may be stateful or stateless. It is stateful.


Stateful

Span It is relatively short-lived. It is relatively long-lived.

Performance It represents a single conversation It encapsulates persistence business data.


with a client.

Accessibility It is created and used by a single It may be shared by multiple clients.


client.
Recovery It is not recoverable in case if EJB It is recoverable if any failure has
server fails. So, it may be destroyed. occurred.

Persistence of It persists data only for the span of Persistence beyond the life of a client
Data the conversation with the client. instance. Persistence can be container-
managed or bean-managed.

Remote It extends [Link]. It extends [Link].


Interface

Home Interface It extends [Link]. It extends [Link].

Bean Class It extends [Link]. It extends [Link].

You might also like