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

Unit - 1 CS-25 - Advance Java Programming (J2ee) : Two-Tier Architecture

The document provides an introduction to J2EE including its architecture, APIs and features. It discusses the two-tier and three-tier architectures. It then covers core J2EE concepts and APIs including Servlets, JSPs, EJBs, JMS, JavaMail and JSF. The last section gives an overview of the J2EE platform and its services.

Uploaded by

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

Unit - 1 CS-25 - Advance Java Programming (J2ee) : Two-Tier Architecture

The document provides an introduction to J2EE including its architecture, APIs and features. It discusses the two-tier and three-tier architectures. It then covers core J2EE concepts and APIs including Servlets, JSPs, EJBs, JMS, JavaMail and JSF. The last section gives an overview of the J2EE platform and its services.

Uploaded by

SANJAY MAKWANA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit – 1 CS-25 - Advance Java Programming

(J2ee)
 Introduction to J2EE :

Today, more and more developers want to write distributed transactional applications for the
enterprise and thereby leverage the speed, security, and reliability of server-side technology. If
you are already working in this area, you know that in the fast-moving and demanding world of
e-commerce and information technology, enterprise applications must be designed, built, and
produced for less money, with greater speed, and with fewer resources than ever before.

To reduce costs and fast-track application design and development, the Java™ 2 Platform,
Enterprise Edition (J2EE™) provides a component-based approach to the design, development,
assembly, and deployment of enterprise applications. The J2EE platform offers a multitier
distributed application model, reusable components, a unified security model, flexible
transaction control, and Web services support through integrated data interchange on Extensible
Markup Language (XML)-based open standards.

 Enterprise Architecture Styles :

Two-Tier Architecture

*The two-tier architecture is also known as the client/server architecture.


*It consists mainly of two tiers:
o   data and
o   client (GUI).
*In two tier architecture always server is the database server(data layer).
*In such physical and data access layer run in one machine
which is nothing but client machine.
*In a two-tier system, we have a client program and a server program. The main difference
between the two is that the server responds to requests from many different clients, while the
clients usually initiate the requests for information from a single node
*This type of architecture suffers from a lack of scalability(Scalability is the capability of a system,
network, or process to handle a growing amount of work) .
*Because both the client and the server have limited resources.
*In addition to the negative effect of network traffic to transfer data to the fat client.
*Another issue is maintainability
*Client side performance is very bad causes Fat(thick) Client

1
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

[ Figure : Two-tier architecture. ]

2
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Three-Tier Architecture

-          To address the issues of the two-tier architecture, the application logic will be placed in its
own tier.
-          Thus applications can be portioned into three tiers.
-          The first tier is referred to as the presentation layer, and consists of the application GUI.
-          The middle tier, or the business layer, consists of the business logic to retrieve data for the
user requests.
-          The back-end tier, or data layer, consists of the data needed by the application.
-          Figure illustrates the three-tier architecture.

[ Figure : Three-tier architecture. ]

Note :- 1
-          The three-tier architecture is the basis for J2EE applications.
-          In which EJBs provide a mechanism to build application logic.
-          While JSPs and servlets abstract the presentation layer and allow interaction with the business
layer.
-          One important feature of the three-tier architecture is sharing system resources by all clients.
-          Which results in :
o   highly efficient,
o   scalable (capable of being easily expanded or upgraded on demand a scalable computer
network),
o   secure, and
o   reliable applications.

3
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Multitier J2EE Architecture

`-          Java EE provides an environment for development and deployment of web-based enterprise
applications using multi-tier architecture, as signified below:

Above diagram demonstrates J2EE multi-tier architecture that surround several J2EE containers
each including its own J2EE components. Here is an overview about the different tiers of J2EE
architecture:

 Client Tier – Components of Client Tier will run in the client devices / containers. Client
Tier components are standalone java applications, static and dynamic HTML pages, and
applets.
 Middle Tier
o Web Tier – The web tier components namely JSP’s and Servlets execute with the
help of J2EE web server in a web container.
o Business Tier – Enterprise Java Beans (EJB) are the business tier components
that are executed within the EJB container using J2EE Application Server.
 EIS Tier – In the EIS (enterprise information system) tier, the application related data are
stored in a database. EIS tier may also include ERP’s or legacy systems that can be
accessed via an API representing Java EE Connector Architecture.

 The J2EE Platform :


Java 2 Platform Enterprise Edition. J2EE is a platform-independent, Java-centric
environment from Sun for developing, building and deploying Web-based enterprise
online applications. The J2EE platform consists of a set of services, APIs, and protocols
that provide the functionality for developing multitier, Web-based applications.

4
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

Some of the key features and services of J2EE:

 At the client tier, J2EE supports pure HTML, as well as Java applets or applications. It
relies on Java Server Pages and servlet code to create HTML or other formatted data for
the client.
 Enterprise JavaBeans (EJBs) provide another layer where the platform's logic is stored.
An EJB server provides functions such as threading, concurrency, security and memory
management. These services are transparent to the author.
 Java Database Connectivity (JDBC), which is the Java equivalent to ODBC, is the
standard interface for Java databases.

 Introduction to J2EE APIs (application program interface) (Servlet, JSP, EJB, JMS,
JavaMail, JSF, JNDI)

Java Servlet Technology

Servlet technology is used to create web application (resides at server side and generates
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was many disadvantages of this technology. We have discussed these
disadvantages below.

Disadvantages of CGI

1. If number of clients increases, it takes more time for sending response.

5
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantage of Servlet

1. Better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language

JavaServer Pages Technology

JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most
of which start with <% and end with %>.

<input type=”text” name=”txt_name” />

<% java code …… %>

<input type=”text” name=”txt”surname”/>

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.

Enterprise JavaBeans Technology

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE
platform has component based architecture to provide multi-tiered, distributed and highly
transactional features to enterprise level applications.

EJB provides an architecture to develop and deploy component based enterprise applications
considering robustness, high scalability, and high performance. An EJB application can be
deployed on any of the application server compliant with the J2EE 1.3 standard specification.

6
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
there are three kinds of enterprise beans: session beans, entity beans, and message-driven beans.
Enterprise beans often interact with databases.

Java Message Service API

The Java Message Service (JMS) API is a messaging standard that allows J2EE application
components to create, send, receive, and read messages. It enables distributed communication
that is loosely coupled, reliable, and asynchronous. JMS is for high-performance, reliable
application-to-application messaging. For eg. you doing a banking transaction thru a ATM

JavaMail API

The JavaMail is an API that is used to compose, write and read electronic messages (emails).
The JavaMail API provides protocol-independent and plateform-independent framework for
sending and receiving mails.The javax.mail and javax.mail.activation packages contains the
core classes of JavaMail API. JavaMail is for writing Java applications that send and receive e-
mail.

JSF

JavaServer Faces (JSF) is a MVC (Model View Controller) web framework that simplifies the construction
of User Interfaces (UI) for server-based applications using reusable UI components in a page.

Java Naming and Directory Interface

The JNDI provides naming and directory functionality. It provides applications with methods for
performing standard directory operations, such as associating attributes with objects and
searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve
any type of named Java object.

 J2EE Containers
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The component-based and platform-independent J2EE
architecture makes J2EE applications easy to write because business logic is organized into
reusable components.In addition, the J2EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these services yourself,
you are free to concentrate on solving the business problem at hand.

Container Services

Containers are the interface between a component and the low-level platform-specific
functionality that supports the component. Before a web component ,enterprise bean, or

7
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
application client component can be executed, it must be assembled into a J2EE module and
deployed into its container. The assembly process involves specifying container settings for each
component in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE server, including services such as
security, transaction management, Java Naming and Directory

J2EE CONTAINERS

Interface™ (JNDI) lookups, and remote connectivity. Here are some of the high-lights:
• The J2EE security model lets you configure a web component or enterprise bean so that system
resources are accessed only by authorized users.
• The J2EE transaction model lets you specify relationships among methods that make up a
single transaction so that all methods in one transaction are treated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming and directory services in
the enterprise so that application components can access naming and directory services.
• The J2EE remote connectivity model manages low-level communications between clients and
enterprise beans. After an enterprise bean is created, a client invokes methods on it as if it were
in the same virtual machine. Because the J2EE architecture provides configurable services,
application components within the same J2EE application can behave differently based on where
they are deployed. For example, an enterprise bean can have security settings that allow it a
certain level of access to database data in one production environment and another level of
database access in another production environment. The container also manages nonconfigurable
services such as enterprise bean and servlet life cycles, database connection resource pooling,
data persistence, and access to the J2EE platform APIs described in section J2EE 1.4
APIs. Although data persistence is a non configurable service, the J2EE architecture lets you
override container-managed persistence by including the appropriate code in your enterprise
bean implementation when you want more control than the default container-managed
persistence provides. For example, you might use bean-managed persistence to implement your
own finder (search) methods or to create a customized database cache.

J2EE Containers
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The component-based and platform-independent J2EE
architecture makes J2EE applications easy to write because business logic is organized into
reusable components. In addition, the J2EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these services yourself,
you are free to concentrate on solving the business problem at hand.

Container Services
Containers are the interface between a component and the low-level platform- specific
functionality that supports the component. Before a web component, enterprise bean, or

8
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
application client component can be executed, it must be assembled into a J2EE module and
deployed into its container .The assembly process involves specifying container settings for each
component in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE server, including services such as
security, transaction management, Java Naming and Directory

Figure 1–5 J2EE Server and Containers

The application server which control and provide services through an interface is  known as a
container. J2EE container helps in deployment and execution of J2EE component. In J2EE
specification we can classify container types as five. Three of these are server-side containers:

 The server, which provides the J2EE runtime environment


 An EJB container that manage EJB components.
 A Web container that manage servlets and JavaServer Pages.

The other two container are client-side:

Application client container


Manages the execution of application client components. Application clients
and their container run on the client.
Applet container
Manages the execution of applets. Consists of a web browser and Java Plug-
in running on the client together.

9
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

 Tomcat as a Web Container

Often referred to as “Apache Tomcat,” Tomcat is not technically an application server at


all – a fact which generates some confusion amongst first-timers, as ‘application server’
and ‘web server’ are all too often used interchangeably.

Rather, Tomcat is more of a web server and web container. This does not mean it lacks
functionality, mind you. An open-source implementation of the Java Servlet, JavaServer
Pages, Java Expression Language, and Java WebSocket Technologies, it is intended as a
platform for powering large-scale, mission-critical web applications. It is used by major
enterprises across several industries , including development, finance, healthcare,
government, ecommerce, retail, and marketing.

1. <form action="process.jsp">  
2. Enter Name:<input type="text" name="name" /><br/><br/>  
3. <input type="submit" value="go"/>  
4. </form>  

 Introduction of JDBC

Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to


connect Java application with Database. JDBC is used to interact with various type of Database
such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the
platform-independent interface between a relational database and Java programming. It allows
java program to execute SQL statement and retrieve result from database.

10
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

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

11
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
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.

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

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

12
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Common JDBC Components

The JDBC API provides the following interfaces and classes −

 JDBC API The JDBC API gives access of programming data from the Java. To use this,
applications can execute SQL statements and retrieve results and updation to the
database. The JDBC API is part of the Java platform, it includes the Java Standard
Edition

 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 sub protocol under JDBC will be
used to establish a database Connection.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.
 The JDBC driver converts the Java data type to the appropriate JDBC type, before
sending it to the database. It uses a default mapping for most data types. For example, a
Java int is converted to an SQL INTEGER. Default mappings were created to provide
consistency between drivers.

 JDBC DataType:
The following table summarizes the default JDBC data type that the Java data type is
converted to, when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.

SQL JDBC/Java setXXX updateXXX


VARCHAR java.lang.String setString updateString
CHAR java.lang.String setString updateString
LONGVARCHAR java.lang.String setString updateString
BIT Boolean setBoolean updateBoolean
NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal
TINYINT Byte setByte updateByte
SMALLINT Short setShort updateShort

13
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
INTEGER Int setInt updateInt
BIGINT Long setLong updateLong
REAL Float setFloat updateFloat
FLOAT Float setFloat updateFloat
DOUBLE Double setDouble updateDouble
VARBINARY byte[ ] setBytes updateBytes
BINARY byte[ ] setBytes updateBytes
DATE java.sql.Date setDate updateDate
TIME java.sql.Time setTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp
CLOB java.sql.Clob setClob updateClob
BLOB java.sql.Blob setBlob updateBlob
ARRAY java.sql.Array setARRAY updateARRAY
REF java.sql.Ref SetRef updateRef
STRUCT java.sql.Struct SetStruct updateStruct

 JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The
ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef()
methods that enable you to directly manipulate the respective data on the server.
 The setXXX() and updateXXX() methods enable you to convert specific Java types to
specific JDBC data types. The methods, setObject() and updateObject(), enable you to
map almost any Java type to a JDBC data type.
 ResultSet object provides corresponding getXXX() method for each data type to retrieve
column value. Each method can be used with column name or by its ordinal position.

 Processing SQL Statements with JDBC

In general, to process any SQL statement with JDBC, you follow these steps:

1. Establishing a connection.
2. Create a statement.
3. Execute the query.
4. Process the ResultSet object.
5. Close the connection.

 Database Exception Handling

Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.

14
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
When an exception condition occurs, an exception is thrown. The term thrown means that
current program execution stops, and the control is redirected to the nearest applicable catch
clause. If no applicable catch clause exists, then the program's execution ends.

JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most
common exception you'll deal with is java.sql.SQLException.

SQLException Methods

An SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.

The passed SQLException object has the following methods available for retrieving additional
information about the exception −

Method Description

getErrorCode( ) Gets the error number associated with the exception.

Gets the JDBC driver's error message for an error,


getMessage( ) handled by the driver or gets the Oracle error number
and message for a database error.

Gets the XOPEN SQLstate string. For a JDBC driver


error, no useful information is returned from this
getSQLState( )
method. For a database error, the five-digit XOPEN
SQLstate code is returned. This method can return null.

getNextException( ) Gets the next Exception object in the exception chain.

Prints the current exception, or throwable, and it's


printStackTrace( )
backtrace to a standard error stream.

Prints this throwable and its backtrace to the print


printStackTrace(PrintStream s)
stream you specify.

Prints this throwable and it's backtrace to the print writer


printStackTrace(PrintWriter w)
you specify.

By utilizing the information available from the Exception object, you can catch an exception and
continue your program appropriately. Here is the general form of a try block −

try {
// Your risky code goes between these curly braces!!!
15
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Example

Study the following example code to understand the usage of try....catch...finally blocks.

//STEP 1. Import required packages


import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
16
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Now, let us compile the above example as follows −

C:\>javac JDBCExample.java
C:\>

When you run JDBCExample, it produces the following result if there is no problem, otherwise
the corresponding error would be caught and error message would be displayed −

C:\>java JDBCExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali

17
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
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:\>

Try the above example by passing wrong database name or wrong username or password and
check the result.

 Discuss types of drivers

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. This driver software is built-in with JDK so no need
to install separately.
 It is a database independent driver.

18
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

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 Vendor client library needs to be installed on client
machine.

19
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
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. Switch facility to switch over
from one database to another database.

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.

20
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

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.

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) {

21
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
. . .
}
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();
}

 PreparedStatement

The PreparedStatement interface is a sub interface of Statement. It is used to execute


parameterized query.

Let's see the example of parameterized query:

22
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
1. String sql="insert into emp values(?,?,?)";  

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}  

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, int


sets the integer value to the given parameter index.
value)

public void setString(int paramIndex,


sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, float


sets the float value to the given parameter index.
value)

public void setDouble(int paramIndex,


sets the double value to the given parameter index.
double value)

executes the query. It is used for create, drop, insert,


public int executeUpdate()
update, delete etc.

executes the select query. It returns an instance of


public ResultSet executeQuery()
ResultSet.

23
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

 CallableStatement

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.

What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output parameters. Function supports only input parameter.

Exception handling using try/catch block can be Exception handling using try/catch can't be used
used in stored procedures. in user defined functions.

How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");  

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");  

It calls the procedure myprocedure that receives 2 arguments.

24
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
This package include classes and interface to perform almost all JDBC operation such as creating
and executing SQL Queries.

Important classes and interface of java.sql package

classes/interface Description
java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures
java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.
java.sql.Date Provide support for Date SQL type.
java.sql.Driver create an instance of a driver with the DriverManager.
java.sql.DriverManager This class manages database drivers.
java.sql.PreparedStatement Used to create and execute parameterized query.
It is an interface that provide methods to access the result row-by-
java.sql.ResultSet
row.
java.sql.Savepoint Specify savepoint in transaction.
java.sql.SQLException Encapsulate all JDBC related exception.
java.sql.Statement This interface is used to execute SQL statements.

 DriverManager: This class loads JDBC drivers in memory. It is a “factory” class and can
also be used to create java.sql.Connection objects to data sources(such as Oracle,
MySQL, etc.).
 Connection: This interface represents a connection with a data source. The Connection
object is used for creating Statement, PreparedStatement, and CallableStatement objects.
 DatabaseMetaData: This interface provides detailed information about the database as a
whole. The Connection object is used for creating Database MetaData objects.
 Statement: This interface represents a static SQL statement. It can be used to retrieve
ResultSet objects.
 PreparedStatement: This interface extends Statement and represents a precompiled SQL
statement. It can be used to retrieve ResultSet objects.
 CallableStatement: This interface represents a database stored procedure. It can execute
stored procedures in a database server.
 ResultSet: This interface represents a database result set generated by using SQL’s
SELECT statement. Statement, PreparedStatement, CallableStatement, and other JDBC
objects can create ResultSet objects.
 ResultSetMetaData: This interface provides information about the types and properties of
the columns in a ResultSet object.
 SQLException: This class is an exception class that provides information on a database
access error or other errors.

25
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

 Java ResultSetMetaData

The metadata means data about data i.e. we can get further information from the data.

If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.

Commonly used methods of ResultSetMetaData interface


Method Description

it returns the total number of columns in the


public int getColumnCount()throws SQLException
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.

public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.

public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

 Java DatabaseMetaData interface

DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.

26
Unit – 1 CS-25 - Advance Java Programming
(J2ee)

Commonly used methods of DatabaseMetaData interface

 public String getDriverName()throws SQLException: it returns the name of the JDBC


driver.
 public String getDriverVersion()throws SQLException: it returns the version number
of the JDBC driver.
 public String getUserName()throws SQLException: it returns the username of the
database.
 public String getDatabaseProductName()throws SQLException: it returns the
product name of the database.
 public String getDatabaseProductVersion()throws SQLException: it returns the
product version of the database.
 public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description of
the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS,
SYSTEM TABLE, SYNONYM etc.

27

You might also like