Unit 4
Unit 4
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.
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 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. }
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.
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
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 run EJB application, you need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc. It performs:
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.
Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.
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).
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.
S.No. EJB JB
Types of EJB
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.
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.
Entity Bean
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:
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.
The following table depicts the key differences between session bean and entity bean.
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.
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.
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.
EJB Container provides the following valuable services for enterprise application
development.
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 −
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 −
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.
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.
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.
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.
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
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.*;
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.
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 −
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);
}
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.
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
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 −
jdbc:oracle:driver:username/password@database
So, the above connection can be created as follows −
import java.util.*;
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();
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.
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.
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.
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.
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 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.
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.*;
Output: