0% found this document useful (0 votes)
6 views

Unit 4

A JavaBean is a reusable Java component that follows certain conventions including having getters and setters and being serializable. JavaBeans benefit from being portable, customizable, and able to receive events from other objects. They also allow exposure of properties and methods to other applications. The document discusses the key aspects of JavaBeans including properties, events, introspection, and customization.

Uploaded by

Akshay Teotia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 4

A JavaBean is a reusable Java component that follows certain conventions including having getters and setters and being serializable. JavaBeans benefit from being portable, customizable, and able to receive events from other objects. They also allow exposure of properties and methods to other applications. The document discusses the key aspects of JavaBeans including properties, events, introspection, and customization.

Uploaded by

Akshay Teotia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit IV

WHAT IS JAVA BEAN?

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.

JavaBeans are software component models. A JavaBean is a general-purpose component


model. A Java Bean is a reusable software component that can be visually manipulated in
builder tools. Their primary goal of a JavaBean is WORA (Write Once Run Anywhere).
JavaBeans should adhere to portability, reusability and interoperability.
JavaBeans will look a plain Java class written with getters and setters methods. It's logical to
wonder: “What is the difference between a Java Bean and an instance of a normal Java
class?” What differentiates Beans from typical Java classes is introspection. Tools that
recognize predefined patterns in method signatures and class definitions can "look inside" a
Bean to determine its properties and behaviour.
A Bean’s state can be manipulated at the time it is being assembled as a part within a larger
application. The application assembly is referred to as design time in contrast to run time.
For this scheme to work, method signatures within Beans must follow a certain pattern, for
introspection tools to recognise how Beans can be manipulated, both at design time, and run
time.

A Java Bean is a reusable software component that can be manipulated visually in a builder
tool. Beans will range greatly in their features and capabilities.

Properties, Methods, and Events of a java Bean

Properties are attributes of a Bean that are referenced by name. These properties are usually
read and written by calling methods on the Bean specifically created for that purpose. A
property of the thermostat component mentioned earlier in the chapter could be the comfort
temperature. A programmer would set or get the value of this property through method calls,
while an application developer using a visual development tool would manipulate the value
of this property using a visual property editor.

The methods of a Bean are just the Java methods exposed by the class that implements the
Bean. These methods represent the interface used to access and manipulate the component.
Usually, the set of public methods defined by the class will map directly to the supported
methods for the Bean, although the Bean developer can choose to expose only a subset of the
public methods.

Events are the mechanism used by one component to send notifications to another. One
component can register its interest in the events generated by another. Whenever the event
occurs, the interested component will be notified by having one of its methods invoked. The
process of registering interest in an event is carried out simply by calling the appropriate
method on the component that is the source of the event. In turn, when an event occurs a
method will be invoked on the component that registered its interest. In most cases, more
than one component can register for event notifications from a single source. The component
that is interested in event notifications is said to be listening for the event.

Introspection

Introspection is the process of exposing the properties, methods, and events that a JavaBean
component supports. This process is used at run-time, as well as by a visual development tool
at design-time. The default behavior of this process allows for the automatic introspection of
any Bean. A low-level reflection mechanism is used to analyze the Bean’s class to determine
its methods. Next it applies some simple design patterns to determine the properties and
events that are supported. To take advantage of reflection, you only need to follow a coding
style that matches the design pattern. This is an important feature of JavaBeans. It means that
you don’t have to do anything more than code your methods using a simple convention. If
you do, your Beans will automatically support introspection without you having to write any
extra code. Design patterns are explained in more detail later in the chapter.

This technique may not be sufficient or suitable for every Bean. Instead, you can choose to
implement a BeanInfo class which provides descriptive information about its associated Bean
explicitly. This is obviously more work than using the default behavior, but it might be
necessary to describe a complex Bean properly. It is important to note that the BeanInfo class
is separate from the Bean that it is describing. This is done so that it is not necessary to carry
the baggage of the BeanInfo within the Bean itself.

If you’re writing a development tool, an Introspector class is provided as part of the Beans
class library. You don’t have to write the code to accomplish the analysis, and every tool
vendor uses the same technique to analyze a Bean. This is important to us as programmers
because we want to be able to choose our development tools and know that the properties,
methods, and events that are exposed for a given component will always be the same

Customization

When you are using a visual development tool to assemble components into applications, you
will be presented with some sort of user interface for customizing Bean attributes. These
attributes may affect the way the Bean operates or the way it looks on the screen. The
application tool you use will be able to determine the properties that a Bean supports and
build a property sheet dynamically. This property sheet will contain editors for each of the
properties supported by the Bean, which you can use to customize the Bean to your liking.
The Beans class library comes with a number of property editors for common types such
as float, boolean, and String. If you are using custom classes for properties, you will have to
create custom property editors to associate with them.

In some cases the default property sheet that is created by the development tool will not be
good enough. You may be working with a Bean that is just too complex to customize easily
using the default sheet. Beans developers have the option of creating a customizer that can
help the user to customize an instance of their Bean. You can even create smart wizards that
guide the user through the customization process.

Customizers are also kept separate from the Bean class so that it is not a burden to the Bean
when it is not being customized. This idea of separation is a common theme in the JavaBeans
architecture. A Bean class only has to implement the functionality it was designed for; all
other supporting features are implemented separately.
Simple example of JavaBean class

1. //Employee.java
2. package mypack;
3. public class Employee implements java.io.Serializable{
4. private int id;
5. private String name;
6. public Employee(){}
7. public void setId(int id){this.id=id;}
8. public int getId(){return id;}
9. public void setName(String name){this.name=name;}
10. public String getName(){return name;}
11. }

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. e.setName("Arjun");//setting value to the object
6. System.out.println(e.getName());
7. }}
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.

There are various advantages of a JavaBean that are as follows.

1. Exposure to other applications


One of the most important advantages of a JavaBean is, the events properties and the methods of a
bean can be exposed directly to another application.

2. Registration to receive events


A JavaBean can be registered to receive events from other objects. However, we can also generate
events that can be sent to other objects.

3. Ease of configuration
We can easily use auxiliary software to configure the JavaBean. However, we can also save the
configuration setting of a JavaBean to persistent storage.

4. Portable
As JavaBeans are built in Java, we can easily port them to any other platform that contains JRE.

5. Lightweight
JavaBeans are light weighted, I.e., we don't need to fulfill any special requirement to use it. Also, it is
very easy to create them. However, it doesn't need a complex system to register components with
JRE.

The other advantages of JavaBeans include reusability, deployment, and customization that can be
archived using JavaBeans.

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.
What is EJB

EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems
to develop secured, robust and scalable distributed applications.

To get information about distributed applications, visit RMI Tutorial first.

To run EJB application, you need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc. It performs:

a. life cycle management,


b. security,
c. transaction management, and
d. object pooling.

EJB application is deployed on the server, so it is called server side component also.

EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from
Java Bean, RMI and Web Services.

When use Enterprise Java Bean?

1. Application needs Remote Access. In other words, it is distributed.


2. Application needs to be scalable. EJB applications supports load balancing, clustering
and fail-over.
3. Application needs encapsulated business logic. EJB application is separated from
presentation and persistent layer.

Types of Enterprise Java Bean

There are 3 types of enterprise bean in java.

Session Bean

Session bean contains business logic that can be invoked by local, remote or webservice client.

Message Driven Bean

Like Session Bean, it contains the business logic but it is invoked by passing message.
Entity Bean

It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API).

EJB Architecture Java

Java beans incorporate a set of objects into one accessible object that can be accessed easily
from any application. This single accessible object is maintainable, customizable, and reusable.
The setter/getter method and the single public constructor are used to govern that single
accessible object. We can update and read the value of any variable of any object by using the
setter and getter, respectively.

The EJB stands for Enterprise Java beans that is a server-based architecture that follows the
specifications and requirements of the enterprise environment. EJB is conceptually based on
the Java RMI(Remote Method Invocation) specification. In EJB, the beans are run in a
container having four-tier architecture. This architecture consists of four layers, i.e., Client
layer, Web layer, Application layer, and Data layer.

Architecture

The EJB architecture has two main layers, i.e., Application Server and EJB Container, based
on which the EJB architecture exist. The graphical representation of the EJB architecture is
given below.

In the above diagram, the logical representation of how EJBs are invoked and deployed by
using RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-
deployed. In order to deploy the containers, it requires the Application server.

Application Server

In the EJB architecture, the Application server is the outermost layer that holds or contains the
Container to be deployed. The application layer plays an important role in executing the
application developed using the beans. It provides the necessary environment to execute those
applications. Some most popular application servers are Web-logic, Tomcat, JBoss, Web-
sphere, Wildfly, and Glass-finish. The main tasks of the application server are:

1. Manage Interfaces
2. Execution of the processes
3. Connecting to the database
4. Manage other resources.

Container

In EJB architecture, the Container is the second outermost layer. It is a very important layer for
enterprise beans that are contained in it. For the enterprise bean, the Container provides various
supporting services, which are as follows:

o It provides support for transactional services such as registering the objects, assign
remote interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed
components.
o It provides support for security services.
o It provides support for the pooling of resources.
o It provides support for managing the Life-cycle of beans and their concurrency.
o It provides support to concentrate on business logic.

Beans

Java beans of the enterprise are installed in the Container in the same way as a Plain old java
object (POJO) is installed and registered to the Container. For developing secured, large scale
and robust business applications, beans provide business logic.

Difference b/w EJB and Java Beans

These are the following differences between EJB and JB:

S.No. EJB JB

1. EJB is not visible because it runs as a remote. JB is visible.

2. EJB is executed on the server-side. EJB can execute on both the


client-side and the server-side.
3. EJB works with an external builder tool or its For interpreting the bean's
IDE. functionality, EJB uses its
external interface.

4. EJB uses the technology of components but By using generic components


cannot build or extend it over beans. created by Java beans, it is able to
build applet and application.

5. It has no property editor, customizer, and bean It has property editors,


information classes. It has only information customizers, and bean
about what is provided by the deployment information classes.
descriptor.

6. It supports transactions. It doesn't support transactions.

7. Three types of EJB possible. No types.

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

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
identify and retrieve specific bean find instances and can be shared by
instances. more than 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


with a client. data.
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 javax.ejb.EJBObject. It extends javax.ejb.EJBObject.


Interface

Home It extends javax.ejb.EJBHome. It extends javax.ejb.EJBHome.


Interface

Bean Class It extends It extends javax.ejb.EJBEntityBean.


javax.ejb.EJBSessionBean.

EJB Container

EJB is a server-side software element that summarizes the business logic of an


application. Enterprise Java Beans web repository yields a runtime domain for web-related
software elements including computer reliability, Java Servlet Lifecycle (JSL) management,
transaction procedure, and other web services.

What is an EJB container?

EJB container is a server-side component that comprises the business logic. It offers local and
remote access to the enterprise beans. In other words, we can say that it provides a runtime
environment for EJB applications within the application server. A single EJB container can
have one or more EJB modules. It acts as an intermediate action between business logic and
enterprise application. The following figure depicts the structure of the EJB container.
The typical behavior envisioned by the Java EE specification is that a developer writes an
Enterprise JavaBean, a simple component, and the EJB container adds the necessary
infrastructure for communications, transactions, and data access. It turns the business logic into
something that executes.

In addition, the EJB container provides lifecycle management for the component to ensure that
its creation, usage, and destruction are both efficient and in accord with the specification. Skip
10sPlay VideoForward Skip 10s

When the EJB container is started, it has, at its highest level, the EJBContainerImpl class as its
controller. It is a subclass of the generic ContainerImpl class. EJBContainerImpl implements
the EJBContainer service interface and has listeners for changes to the deployed application
modules and other parts of the environment.

What does an EJB container do?

EJB Container Services

EJB Container provides the following valuable services for enterprise application
development.

o Transaction support (start, rollback, and commit)


o Security Model
o Persistence Support
o Timing Services and Job Scheduling
o Messaging
o Remote Access
o Distribution
o Web-services
o Component Pooling
o Component Life-cycle
What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.

Pre-Requisite

Before moving further, you need to have a good understanding of the following two subjects

 Core JAVA Programming
 SQL or MySQL Database

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

Common JDBC Components

The JDBC API provides the following interfaces and classes −


 DriverManager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
 Driver − This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
 Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
 Statement − You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
 ResultSet − These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move through
its data.
 SQLException − This class handles any errors that occur in a database application.

What is JDBC Driver?

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact
with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.
JDBC Drivers Types

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1 − JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2 − JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
If we change the Database, we have to change the native API, as it is specific to a database
and they are mostly obsolete now, but you may realize some speed increase with a Type 2
driver, because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3 − JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4 − 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Which Driver should be Used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is
the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
Creating JDBC Application

There are following six steps involved in building a JDBC application −


 Import the packages − Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
 Execute a query − Requires using an object of type Statement for building and
submitting an SQL statement to the database.
 Extract data from result set − Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set.
 Clean up the environment − Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

Sample Code

This sample example can serve as a template when you need to create your own JDBC
application in the future.
This sample code has been written based on the environment and database setup done in the
previous chapter.
Copy and paste the following example in FirstExample.java, compile and run as follows −

import java.sql.*;

public class FirstExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −

C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

After you've installed the appropriate driver, it is time to establish a database connection
using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps −
 Import JDBC Packages − Add import statements to your Java program to import
required classes in your Java code.
 Register JDBC Driver − This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
 Database URL Formulation − This is to create a properly formatted address that points
to the database to which you wish to connect.
 Create Connection Object − Finally, code a call to
the DriverManager object's getConnection( ) method to establish actual database
connection.

Import JDBC Packages

The Import statements tell the Java compiler where to find the classes you reference in your
code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data
in SQL tables, add the following imports to your source code −

import java.sql.* ; // for standard JDBC programs


import java.math.* ; // for BigDecimal and BigInteger support
Register JDBC Driver

You must register the driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into the memory, so it can be utilized
as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one of
two ways.

Approach I - Class.forName()

The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.
The following example uses Class.forName( ) to register the Oracle driver −

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll have
to code for two extra Exceptions as follows −

try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}

Approach II - DriverManager.registerDriver()

The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver −

try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL Formulation

After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

All the highlighted part in URL format is static and you need to change only the remaining part
as per your database setup.
Create Connection Object

We have listed down three forms of DriverManager.getConnection() method to create a


connection object.

Using a Database URL with a username and password

The most commonly used form of getConnection() requires you to pass a database URL,
a username, and a password −
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value
for the database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete
database URL would be −

jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and password to
get a Connection object as follows −

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);

Using Only a Database URL

A second form of the DriverManager.getConnection( ) method requires only a database URL



DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password and has the
following general form −

jdbc:oracle:driver:username/password@database
So, the above connection can be created as follows −

String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";


Connection conn = DriverManager.getConnection(URL);

Using a Database URL and a Properties Object

A third form of the DriverManager.getConnection( ) method requires a database URL and a


Properties object −

DriverManager.getConnection(String url, Properties info);


A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to
the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code −

import java.util.*;

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );

Connection conn = DriverManager.getConnection(URL, info);

Closing JDBC Connections

At the end of your JDBC program, it is required explicitly to close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will
close the connection when it cleans up stale objects.
Relying on the garbage collection, especially in database programming, is a very poor
programming practice. You should make a habit of always closing the connection with the
close() method associated with connection object.
To ensure that a connection is closed, you could provide a 'finally' block in your code.
A finally block always executes, regardless of an exception occurs or not.
To close the above opened connection, you should call close() method as follows −
conn.close();

JDBC - Statements, PreparedStatement


Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties
that enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
The following table provides a summary of each interface's purpose to decide on the interface
to use.
Interfaces Recommended Use

Statement Use this for general-purpose access to your database. Useful when you
are using static SQL statements at runtime. The Statement interface
cannot accept parameters.

PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.

CallableStatement Use this when you want to access the database stored procedures. The
CallableStatement interface can also accept runtime input parameters.

The Statement Objects

Creating Statement Object


Before you can use a Statement object to execute a SQL statement, you need to create one
using the Connection object's createStatement( ) method, as in the following example −

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.
 boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.
 int executeUpdate (String SQL) − Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for which
you expect to get a number of rows affected - for example, an INSERT, UPDATE, or
DELETE statement.
 ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Closing Statement Object

Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the Statement object as well. However, you should always explicitly close the
Statement object to ensure proper cleanup.

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}
For a better understanding, we suggest you to study the Statement - Example tutorial.

The PreparedStatement Objects

The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.

Creating PreparedStatement Object

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents position
1, the next position 2, and so forth. This method differs from that of Java array indices, which
starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.

Closing PreparedStatement Object

Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the PreparedStatement object as well. However, you should always explicitly close
the PreparedStatement object to ensure proper cleanup.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}

How to Call Stored Functions and Stored Procedures using


JDBC?

JDBC or Java Database Connectivity is a Java API to connect and execute the query with
the database. It is a specification from Sun microsystems that provides a standard
abstraction(API or Protocol) for java applications to communicate with various databases.
It provides the language with java database connectivity standards. It is used to write
programs required to access databases.
Stored Procedure
Stored procedure is a set of SQL statements stored together as a single block of code in
the database which can be reused multiple times without having to write the queries
again. A stored procedure may provide multiple output values and accepts input as well as
output parameters.
Stored Function
Stored function is a set of SQL statements that perform a particular task. It is similar to a
stored procedure except that it returns a single value and accepts only input parameters.
Advantages of using Stored Procedures and Stored Functions
 Stored procedures and functions are stored in the database and can be called as and
when required.
 Business and database logic can be stored in the database itself which can be used by
multiple applications.
 Reduces traffic. No need to send the set of queries over the network. Rather
procedures and functions are stored in the database and a call to these stored
procedures and functions can be made to fetch the results.
 This leads to fast execution as they are compiled once and used multiple times.
Stored Procedures vs Stored Functions
Stored Procedure Stored Function

A stored procedure can return zero or more


values. A stored function returns a single value.

A stored procedure accepts IN, OUT, and A stored function accepts IN parameters
INOUT parameters only.

A stored procedure can call a stored A stored function cannot call a stored
function within its body. procedure.

A stored procedure can use all DML A stored function can only use the SELECT
statements within its body. statement.

A stored procedure can use try-catch blocks A stored function cannot use try-catch
for exception handling. blocks.

A stored procedure cannot be embedded A stored function can be embedded into


into SELECT/WHERE/HAVING etc. clauses. SELECT/WHERE/HAVING etc. clauses.

Syntax of stored procedures and functions


Stored Procedure:
DELIMITER $$
CREATE PROCEDURE <procedure_name> ([IN|OUT|INOUT] <parameter_name>
DATATYPE,...)
BEGIN
--statements--
END$$
DELIMITER ;
Stored Function:
DELIMITER $$
CREATE FUNCTION <function_name>(<parameter_name> DATATYPE,...) RETURNS
RETURN_TYPE
[NOT] DETERMINISTIC
BEGIN
--statements--
END$$
DELIMITER ;
Types of parameters
1. IN parameter: It is the default parameter type used to provide input values to a
procedure or a function.
2. OUT parameter: It is used to fetch output values from a procedure. No initial value is
provided to an OUT parameter. Its value is set by the procedure and returned.
3. INOUT parameter: It is similar to the OUT parameter except that it is provided with an
initial value that is modified by the procedure and returned.
Calling stored procedures and functions using JDBC
Callable Statements:
Callable Statements in JDBC are used to call stored procedures and functions from the
database. CallableStatement is an interface present in java.sql package. Following method
of java.sql.Connection is used to get the object of CallableStatement.
CallableStatement prepareCall(String sql) throws SQLException
Given below are some useful methods of CallableStatement:
 boolean execute() throws SQLException
 int executeUpdate() throws SQLException
 int getInt(int parameterIndex) throws SQLException
 void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
 void setInt(String parameterName, int x) throws SQLException
Example 1:
createEmp.sql
drop table if exists emp;
create table emp(emp_id int primary key,emp_name varchar(20),salary decimal(10,2));
insert into emp values(101,"Ansh",20000);
insert into emp values(102,"Danish",16000);
insert into emp values(103,"Priya",30000);

updateEmpSalary.sql
drop procedure if exists updateEmpSalary;
DELIMITER $$
CREATE PROCEDURE updateEmpSalary(IN id INT,IN incRate DECIMAL(4,2))
BEGIN
UPDATE emp
SET salary = salary*(1+incRate)
WHERE emp_id=id;
END$$
DELIMITER ;

UpdateEmpSalary.java
 Java

import java.sql.*;

public class UpdateEmpSalary {


public static void main(String[] args) {
Connection con=null;
try
{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gfg","root","root");
CallableStatement cs=con.prepareCall("{call updateEmpSalary(?,?)}");
cs.setInt(1,101);
cs.setDouble(2,0.1);
cs.executeUpdate();
}
catch (Exception e)
{
System.out.println(e);
}
finally {
try
{ con.close();
}
catch (SQLException e)
{
System.out.println(e);
}
}
}
}

Output:

You might also like