Вы находитесь на странице: 1из 86

UNIT-1

ENTERPRISE FOUNDATIONS
ENTERPRISE ARCHITECTURAL OVERVIEW
The Components of an Enterprise System
ENTERPRISE ARCHITECTURAL OVERVIEW
Information Technology in Enterprise System
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Enterprise Objects
– Stage 1:Assembly Language Programming

– Stage 2:Early High Level Language Programming

– Stage 3:Modular Programming

– Stage 4:Functional Programming

– Stage 5:Object Oriented Programming


OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Elements of Object Oriented Software


– Class
• Data
• Method
• Object- Represent an instance of a class in memory
• The state of the object is defined by the values assumed by the
class fields
• The behavior of the object is a function of the method
implementations, the return values from the method calls, and
the state change of the object
• Visibility levels associated with class fields and methods can
define what level of access other classes have to those fields and
methods
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Elements of Object Oriented Software


– Class
• Private visibility
• Public visibility
• Protected visibility
• Inheritance means that a class B, for example, can be defined
such that it inherits the behavior of a class A from which it is
inherited
• Classes have class names that are scoped according to a class
package
• A package refers to a collection of one or more classes
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Object Oriented S/W Importance to the Enterprise


– OO as a software-development paradigm is one of most
important foundations and enablers for building
successful and expandable large-scale distributed
enterprise systems
– OO practices foster the development of modular
programs with encapsulated state and implementation
behavior, as well as facilitate the abstraction of problems
– Modularity, encapsulation, abstraction, and reuse are
rudimentary programming tenets that help in making
large-scale distributed enterprise projects a reality
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• The Object Oriented Development Process


– Development Process Overview
• Project Charter
– Establish a charter detailing goals and objectives for the effort
to be undertaken
• Requirements Analysis
– Perform analysis of expected system behavior and system
interfaces
• Preliminary System Design
– Perform a preliminary design of a system with consideration for
Commercial Off the Shelf (COTS) software, custom software,
and reuse. Partition design into smaller problems to solve
• Detailed Design
– Perform detailed design of core classes and interfaces
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• The Object Oriented Development Process


– Development Process Overview
• Implementation
– Implement the software. May involve custom code writing, as well
as integrating with COTS
• Unit Test
– Unit test the implementation
• Assembly
– Assemble individual elements into discrete elements of behavior
• Thread Test
– Test threads of behavior on assembled elements
• Configuration Specification
– Define the assumed COTS and custom software configure tion and
versions
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• The Object Oriented Development Process


• System Test
– Test a fully assembled and configured system
• Deployment
– Deploy the system per the configuration specification
• Maintenance
– Maintain operational software for bug fixes and upgrades.
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Iteration and Phases of Development


– Iteration 1
• Follow above given 12 steps
– Iteration 2
• Repeat above given 12 steps
– Iteration 3
• Repeat above given 12 steps
– Iteration 4
• Repeat above given 12 steps
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Unified Modeling Language


– Structural Modeling Diagrams
• Package diagrams
• Class or Structural diagrams
• Object diagrams
• Component diagrams
• Deployment diagrams
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Unified Modeling Language


– Behavioral Modeling Diagrams
• Use Case diagrams
• Activity diagrams
• State Machine diagrams
• Communication diagrams
• Sequence diagrams
• Timing diagrams
• Interaction Overview diagrams
OBJECT ORIENTED SOFTWARE DEVELOPMENT FOR
THE ENTERPRISE

• Unified Modeling Language


– Classes, Class Names, Class Package, Class
Attributes, Class Operations, Visibility,
Stereotypes, Attribute syntax, Static attributes
– Associations, Navigatability, Multiplicity,
Aggregation, Uses relations, Inheritance,
Interface, OR-Association, Notes
JAVA ENTERPRISE SYSTEM

• J2EE Model
• J2EE Features
– Specification
• The J2EE specification defines the requirements that a J2EE vendor
product implementation must satisfy
– Programming model
• The programming model is cast in the form of a developer's guide
explaining how application developers might use various aspects of
the J2EE. The guide is primarily described at a conceptual and very
high level with a sample application at the end of the guide
– Platform
• The J2EE platform is the set of integrated enterprise API library
software and development tools. The J2EE platform depends on
installation of the J2SE v1.2 platform
JAVA ENTERPRISE SYSTEM

• J2EE Features
– Reference Implementation
• The J2EE reference implementation is a sample
implementation of the underlying services utilized by
the J2EE platform APIs. It is primarily meant to be used
in early development and prototyping environments
– Compatibility Test Suite
• The compatibility test suite is used by vendors to
determine whether their implementation of the J2EE
services satisfies the J2EE specification requirements
JAVA ENTERPRISE SYSTEM

• J2EE Component-Container Architecture


– J2SE Platform
• The standard J2SE v1.2 Java runtime environment atop of which
the J2EE operates
– Java Enterprise APIs
• A collection of standard Java enterprise API versions
– Java Enterprise Implementations
• Any Java enterprise service provider implementations of the Java
enterprise APIs
– Deployment Services
• An environment for configurable deploying J2EE components
– Management Services
• Management services offered by the container for providing an
efficient, scalable, and dependable computing environment
JAVA ENTERPRISE SYSTEM

• J2EE Component-Container Architecture


– The four J2EE component-container models are
described here
• EJB Application Servers
• Web Application Servers
• Applet Clients
• Application Clients
JAVA ENTERPRISE SYSTEM

• J2EE Component-Container Architecture


– The four J2EE component-container models are
described here
• EJB Application Container
• Web Application Container
• Applet Container
• Application Container
JAVA ENTERPRISE SYSTEM

• J2EE Restriction
– EJB Application Servers
• EJB application components can queue print jobs, create socket
connections as a client (but not server connections), and read
system properties
– Web Application Servers
• Web components can also queue print jobs, create socket
connections as a client, and read system properties. Additionally,
Web components can load external libraries and can read and
write files
– Applet Clients
• Applet components can only connect to the server defined within
its CODEBASE and can read a limited set of properties
JAVA ENTERPRISE SYSTEM

• J2EE Restriction
– Application Clients
• Application client components have the most freedom
out of all J2EE-component types
• Application clients can create socket connections as a
client and accept and listen for socket connections as a
server on a local machine's ports above and including
port 1024
• Application clients can also read system properties,
queue print jobs, exit a JVM process, and load external
libraries
JAVA ENTERPRISE SYSTEM
LOGICAL ARCHITECTURE
JAVA ENTERPRISE SYSTEM

• Database Connectivity
– Data Connectivity
• Defines most of the basic JDBC functionality
– JDBC 2.0 Core API
• Includes all the functionality contained in the JDBC 1.0 version
plus a host of new features for managing query results and
manipulating new data types. The JDBC 2.0 core API is included
with the J2SE, and with the J2EE by virtue of its inclusion with the
J2SE
– JDBC 2.0 Standard Extension API
• Offers a range of more sophisticated enterprise features useful in
middle-tier servers for managing scalable database access
JAVA ENTERPRISE SYSTEM

• Communication Mechanisms
– TCP/IP
– WEB/HTTP
– CORBA/IIOP
– RMI/JRMP
– RMI/IIOP
– DCOM
– Distributed Common Services
• Naming Services, Directory Services, Trading Services, Activation Services,
Messaging Services, Transaction Services
JAVA ENTERPRISE SYSTEM
• Assurance Mechanisms
– Security
• The likelihood that your system will operate in a secure and security
breach–free fashion
– Reliability
• The likelihood that your system will operate correctly and as
intended
– Availability
• The likelihood that your system will actually be operational and
offering service. Scalability of your system to support growth in
usage is one aspect of availability
– Maintainability
• The likelihood that your system will be capable of being maintained,
upgraded, and extended for future growth
– Safety
• The likelihood that your system will operate in a safe and accident-
free manner
JAVA ENTERPRISE SYSTEM

• Client Connectivity
– Java Client
– Java Applet Client
– Web browser based client
– Non Java Client
– Dcom Based Client

• Web Connectivity
– Servlet, Jsp, HTML, XML
• Application Connectivity
– Java based Client to Non Java Based Server
– Non Java Based Client to Java Based Server
JAVA ENTERPRISE SYSTEM

• The J2EE Future


– Application Client Service Enhancements
– Service Provider Interfaces
– JDBC 2.0 Extension Implementation
– RMI/IIOP Implementation
– IIOP Communication
– JMS Implementations
– Asynchronous EJB Messages
– JTA Implementations
– Security Authentication and Authorization
– Security Auditing
– Security Permission Extensions
– Security Interoperability
– Transaction Interoperability
– EAI Connectors
– XML APIs
– Administration Tools
ENTERPRISE DATA
• Database Basics
– Data Model Abstraction Levels
– General DBMS Architecture
– Transaction
• Relational Databases
– RDMS Architecture
– SQL
– Data model Diagram
• Object Databases
– ODBMS Architecture
• RDBMS vs ODBMS
• Relational/Object Translations
• CLIs- A Call Level Interface
• Embedded SQL
• ODBC-Open Database Connectivity
• JDBC—Java Database Connectivity
BASIS OF JDBC

• JDBC Architecture
• JDBC Drivers and Their Types
• JDBC Driver Configuration
• JDBC Connections
• JDBC Statements
• JDBC Result set
• Sql and Java Mapping
• JDBC MetaData
BASIS OF JDBC

• JDBC Architecture
BASIS OF JDBC

• JDBC
– Java Database Connectivity (JDBC) is a standard Java API to interact with relational
databases form Java.
– JDBC has set of classes and interfaces which can use from Java application and talk to
database without learning RDBMS details and using Database Specific JDBC Drivers.
• JDBC Architecture
– The JDBC API, which provides the application-to-JDBC Manager connection
– The JDBC Driver API, which 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 database
– The location of the driver manager with respect to the JDBC drivers and the Java
application is shown in Figure 1
BASIS OF JDBC
• Main components of JDBC
– DriverManager
• Manages a list of database drivers
• Matches connection requests from the java application with the proper database driver
using communication subprotocol
• The first driver that recognizes a certain subprotocol under JDBC will be used to
establish a database Connection
– Driver
• The database communications link, handling all communication with the database.
Normally, once the driver is loaded, the developer need not call it explicitly
– Connection
• 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
• Encapsulates an SQL statement which is passed to the database to be parsed,
compiled, planned and executed.
– ResultSet
• The ResultSet represents set of rows retrieved due to query execution
BASIS OF JDBC
• How the JDBC application works
– A JDBC application can be logically divided into two layers:
• Driver layer
• Application layer
• Driver layer consists of DriverManager class and the
available JDBC drivers
• The application begins with requesting the DriverManager
for the connection
• An appropriate driver is choosen and is used for establishing
the connection. This connection is given to the application
which falls under the application layer
• The application uses this connection to create Statement
kind of objects, through which SQL commands are sent to
backend and obtain the results
BASIS OF JDBC

• How the JDBC application works


– A JDBC application can be logically divided into two layers:
BASIS OF JDBC

• JDBC Drivers and Their Types


– Type 1:JDBC-ODBC Bridge(Vendor Independent-Client Side Native)
– Type 2:Native API Partly Java Technology Enabled(Vendor Specific-Client Side Native)
– Type3:Net Protocol Fully Java Technology Enabled(Vendor Independent-Remote
Network Listener)
– Type4:Native Protocol Fully Java Technology Enabled(Vendor Specific- Independent-
Remote Network Listener)
BASIS OF JDBC

• Type 1: JDBC-ODBC Bridge driver (Bridge)


– The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC
driver
– ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for
experimental use or when no other alternative is available

• Advantage
• The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available
• Disadvantages
– Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable
– A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver,
then to the database, and this applies even in the reverse process. They are the
slowest of all driver types
– The client system requires the ODBC Installation to use the driver
– Not good for the Web
BASIS OF JDBC

– Type 1
BASIS OF JDBC
• Type 2 JDBC Driver
– Native-API/partly Java driver
– The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls
into database-specific calls
– i.e. this driver is specific to a particular database
– Some distinctive characteristic of type 2 jdbc drivers are shown below
– Example: Oracle will have oracle native api
• Advantage
– The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than
that of Type 1 and also it uses Native api which is Database specific
• Disadvantage
– Native API must be installed in the Client System and hence type 2 drivers cannot be used
for the Internet
– Like Type 1 drivers, it’s not written in Java Language which forms a portability issue
– If we change the Database we have to change the native api as it is specific to a database
– Mostly obsolete now
– Usually not thread safe
BASIS OF JDBC
• Type 2 JDBC Driver(Native-API/partly Java driver)
BASIS OF JDBC
• Type 3 JDBC Driver
– All Java/Net-protocol driver
– Type 3 database requests are passed through the network to the middle-tier server
– The middle-tier then translates the request to the database. If the middle-tier server can in
turn use Type1, Type 2 or Type 4 drivers
• Advantage
– This driver is server-based, so there is no need for any vendor database library to be present
on client machines
– This driver is fully written in Java and hence Portable. It is suitable for the web
– There are many opportunities to optimize portability, performance, and scalability
– The net protocol can be designed to make the client JDBC driver very small and fast to load
– The type 3 driver typically provides support for features such as caching (connections, query
results, and so on), load balancing, and advanced system administration such as logging and
auditing
– This driver is very flexible allows access to multiple databases using one driver
– They are the most efficient amongst all driver types
• Disadvantage
– It requires another server application to install and maintain
– Traversing the recordset may take longer, since the data comes through the backend server
BASIS OF JDBC
• Type 3 JDBC Driver
• All Java/Net-protocol driver
BASIS OF JDBC
• Type 4 JDBC Driver
• Native-protocol/all-Java driver
– The Type 4 uses java networking libraries to communicate directly with the
database server
• Advantage
– The major benefit of using a type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence and eliminate deployment
administration issues. It is most suitable for the web
– Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to
pass the request on to another server, performance is typically quite good
– You don’t need to install special software on the client or server. Further,
these drivers can be downloaded dynamically

• Disadvantage
– With type 4 drivers, the user needs a different driver for each database.
BASIS OF JDBC
• Type 4 JDBC Driver
• Native-protocol/all-Java driver
BASIS OF JDBC
• Basic Steps in writing a Java program using JDBC
– Load the RDBMS specific JDBC driver because this driver actually
communicates with the database
– Open the connection to database which is then used to send SQL statements
and get results back
– Create JDBC Statement object. This object contains SQL query
– Execute statement which returns resultset(s). ResultSet contains the tuples
of database table as a result of SQL query
– Process the result set
– Close the connection
BASIS OF JDBC
• What is Statement
– Statement acts like a vehicle through which SQL commands can be sent
– Through the connection object we create statement kind of objects
– Statement stmt = conn.createStatement();
– This method returns object which implements statement interface
• PreparedStatement
– A prepared statement is an SQL statement that is precompiled by the database
– Through precompilation, prepared statements improve the performance of SQL
commands that are executed multiple times (given that the database supports
prepared statements)
– Once compiled, prepared statements can be customized prior to each execution by
altering predefined SQL parameters

• PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ?


WHERE ID = ?");
• pstmt.setBigDecimal(1, 153833.00);
• pstmt.setInt(2, 110592);
• Here: conn is an instance of the Connection class and "?" represents parameters.These
parameters must be specified before execution.
BASIS OF JDBC
• What are callable statements
– Callable statements are used from JDBC application to invoke stored
procedures and functions
• How to call a stored procedure from JDBC
– PL/SQL stored procedures are called from within JDBC programs by means of the
prepareCall() method of the Connection object created
– A call to this method takes variable bind parameters as input parameters as well as
output variables and creates an object instance of the CallableStatement class

– The following line of code illustrates this:


• CallableStatement stproc_stmt =
conn.prepareCall("{call procname(?,?,?)}");
Here conn is an instance of the Connection class
BASIS OF JDBC
• What are the standard isolation levels defined by JDBC
– TRANSACTION_NONE
– TRANSACTION_READ_COMMITTED
– TRANSACTION_READ_UNCOMMITTED
– TRANSACTION_REPEATABLE_READ
– TRANSACTION_SERIALIZABLE
• What is resultset
• The ResultSet represents set of rows retrieved due to
query execution.
• ResultSet rs = stmt.executeQuery(sqlQuery);
BASIS OF JDBC
• JDBC Basics – Java Database Connectivity Steps
• import the java.sql package
• 1. Loading a database driver,
– we load the driver class by calling Class.forName() with the Driver
class name as an argument
– Once loaded, the Driver class creates an instance of itself
– A client can connect to Database Server through JDBC Driver
– Since most of the Database servers support ODBC driver therefore
JDBC-ODBC Bridge driver is commonly used
– The return type of the Class.forName (String ClassName) method is
“Class”. Class is a class in java.lang package
– try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other
driver }
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}
BASIS OF JDBC
• 2. Creating a oracle jdbc Connection
• The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver
• DriverManager is considered the backbone of JDBC architecture
• DriverManager class manages the JDBC drivers that are installed on the
system
• Its getConnection() method is used to establish a connection to a database
• It uses a username, password, and a jdbc url to establish a connection to the
database and returns a connection object
• A jdbc Connection represents a session/connection with a specific database
• Within the context of a Connection, SQL, PL/SQL statements are executed and
results are returned
• An application can have one or more connections with a single database, or it
can have many connections with different databases
• A Connection object provides metadata i.e. information about the database,
tables, and fields
• It also contains methods to deal with transactions
BASIS OF JDBC
• 2. Creating a oracle jdbc Connection
• JDBC URL Syntax:: jdbc: <subprotocol>: <subname>
• Each driver has its own subprotocol
• Each subprotocol has its own syntax for the source
• We’re using the jdbc odbc subprotocol
• so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver
• try{
Connection
dbConnection=DriverManager.getConnection(url,”loginName”,”Pass
word”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}
BASIS OF JDBC
• Creating a jdbc Statement object,
• Once a connection is obtained we can interact with the database
• Connection interface defines methods for interacting with the database
via the established connection
• To execute SQL statements, you need to instantiate a Statement object
from your connection object by using the createStatement() method
• Statement statement = dbConnection.createStatement();
• A statement object is used to send and execute SQL statements to a
database.
• Three kinds of Statements
• Statement:
– Execute simple sql queries without parameters.
– Statement createStatement()
– Creates an SQL Statement object.
BASIS OF JDBC
• Three kinds of Statements
• Prepared Statement :
– Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
– returns a new PreparedStatement object. PreparedStatement objects are
precompiled SQL statements
• Callable Statement:
– Execute a call to a database stored procedure
– CallableStatement prepareCall(String sql)
– returns a new CallableStatement object. CallableStatement objects are SQL
stored procedure call statements
BASIS OF JDBC
• Executing a SQL statement with the Statement object, and returning a jdbc
resultSet
• Statement interface defines methods that are used to interact with database via
the execution of SQL statements
• The Statement class has three methods for executing statements:
• executeQuery(), executeUpdate(), and execute()
• For a SELECT statement, the method to use is executeQuery
• For statements that create or modify tables, the method to use is executeUpdate
• Note: Statements that create a table, alter a table, or drop a table are all
examples of DDL
• statements and are executed with the method executeUpdate
• execute() executes an SQL statement that is written as String object
BASIS OF JDBC
• ResultSet
– provides access to a table of data generated by executing a Statement
– The table rows are retrieved in sequence
– A ResultSet maintains a cursor pointing to its current row of data
– The next() method is used to successively step through the rows of the
tabular results

• ResultSetMetaData
– Interface holds information on the types and properties of the columns in a ResultSet.
It is constructed from the Connection object
BASIS OF JDBC
• DATABASE URLs
– A database Uniform Resource Locator (URL) represents a fully
qualified database connection name identifying the database and
database driver to which you are connecting
– jdbc:subprotocol:subname
– jdbc is a database driver type keyword used in the URL for all JDBC
database URLs
– subprotocol represents the type of database to which one desires
connectivity
– subname provides additional information needed by the database
type for establishing connectivity.
• The subprotocol and subname to use for a particular database instance
should be described in your JDBC driver vendor's documentation
• but some examples are listed here for different driver types
BASIS OF JDBC
• DATABASE URLs
– Type 1: JDBC-ODBC Bridge Driver URLs
• jdbc:odbc:customer;UID:dba;pwd:dba
• jdbc:odbc:customer;CacheSize=100
• jdbc:odbc:<datasource name>;param=value;param=value;….

– Type 2: Native-API Partly Java Technology-Enabled Driver URL


• jdbc:oracle:oci7:@SQLNETinstance Name
– Type 3: Net-Protocol Fully Java Technology-Enabled Driver URL
• jdbc:dbAnywhere:1529
– Type 4: Native-Protocol Fully Java Technology-Enabled Driver URLs
• jdbc:oracle:thin:@<machine name>:<port
Number>:<DBMS instancename>
BASIS OF JDBC
• Creating Connections
– DriverManager's getConnection() methods must be invoked with the
database URL as a parameter
– Three forms of getConnection() exist on the DriverManager class
– getConnection(String url) simply attempts to connect given the databaseURL
– getConnection(String url, String user, String password) attempts to connect
given the database URL, a database username, and the database user‘s
password.
– getConnection(String url, java.util.Properties info) attempts to connect given
the database URL and a set of properties used as connection arguments.
Sometimes, a user and password property are passed in via the Properties
object

– ResultSet executeQuery(); to execute SQL queries and obtain a ResultSet


object
– int executeUpdate(); to execute SQL updates and obtain a count of
updated rows
– boolean execute(); to execute SQL DDL commands and obtain a boolean
value indicating whether a ResultSet was created
BASIS OF JDBC
• SQL and JAVA Mapping

From SQL Type To Java Language Type


CHAR java.lang.String
VARCHAR java.lang.String
LONGVARCHAR java.lang.String
BIT boolean
BINARY byte[ ]
VARBINARY byte[ ]
LONGVARBINARY byte[ ]
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
BASIS OF JDBC
• SQL and JAVA Mapping

From SQL Type To Java Language Type


DOUBLE double
NUMERIC java.lang.math.BigDecimal
DECIMAL java.lang.math.BigDecimal
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
BASIS OF JDBC
• JAVA and SQL Mapping
From Java Language Type To SQL TYPE
String VARCHAR or LONGVARCHAR
boolean BIT
byte [ ] VARBINARY or
LONGVARBINARY
byte TINYINT
short SMALLINT
int INTEGER
long BIGINT
float REAL
double DOUBLE
java.math.BigDecimal NUMERIC
java.sql.Date DATE
java.sql.Date TIME
java.sql.Date TIMESTAMP
BASIS OF JDBC
• JDBC MetaData
– JDBC Meta Data is the collective information about the data structure and
property of a column available in table
– The meta data of any table tells you the name of the columns,datatype used
in column and constraint used to enter the value of data into column of the
table
– getMetaData ( ) - The Result Set call get Metadata( ),which return you the
property of the retrieve record set (length,field,column).Meta Data account
for data element and its attribute
– ResultSetMetaData metaData = rs.getMetaData();
– int rowCount = metaData.getColumnCount();
– metaData.getTableName()
– metaData.getColumnName ()
– metaData.getColumnDisplaySize ()
– metaData.getColumnTypeName ()
ADVANCED JDBC FEATURES

• Scrollable Result Sets


• Updateable Result Sets
• Batch Updates
• Advanced Data Types
• Row Sets
• Stored Procedures
• Database Naming
• Connection Pools
• Distributed Transaction
ADVANCED JDBC FEATURES

• Scrollable Result Sets


– TYPE_FORWARD_ONLY
• the result set is not scrollable i.e. the cursor moves only forward, from
before the first row to after the last row
– TYPE_SCROLL_INSENSITIVE
• the result set is scrollable; its cursor can move both forward and
backward relative to the current position,
and it can move to an absolute position.
– TYPE_SCROLL_SENSITIVE
• the result set is scrollable; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute
position
ADVANCED JDBC FEATURES

• Scrollable Result Sets


– Before you can take advantage of these features, however, you need to
create a scrollable ResultSet object
– The following line of code illustrates one way to create a scrollable ResultSet
object
• Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(".....");
• The first argument is one of three constants added to the
ResultSet API to indicate the type of a ResultSet object:
TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and
TYPE_SCROLL_SENSITIVE
ADVANCED JDBC FEATURES

• Updateable Result Sets


– Read-only
– Updateable
– A default ResultSet object is not updatable and has a cursor that
moves forward only
– You can iterate through it only once and only from the first row to
the last row
– It is possible to produce ResultSet objects that are scrollable and/or
updatable
– An updatable result set allows modification to data in a table
through the result set
ADVANCED JDBC FEATURES

• Updateable Result Sets


– try {
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE); CONCUR_READ_ONLY

ResultSet resultSet = stmt.executeQuery(


"SELECT EmployeeID, Name, Office FROM employees");
} catch (SQLException e) {
}
– to update a column value in the current row
– In a scrollable ResultSet object, the cursor can be
moved backwards and forwards, to an absolute
position, or to a position relative to the current row
ADVANCED JDBC FEATURES

• Updateable Result Sets


– The following code fragment updates the Office column in the fifth row of
the ResultSet object rs and then uses the method updateRow to update the
data source table from which rs was derived

– rs.absolute(5); // moves the cursor to the fifth row of rs

– rs.updateString("Office", "HQ222"); // updates the


// Office column of row 5 to be HQ222

rs.updateRow(); // updates the row in the data source


ADVANCED JDBC FEATURES

• Updateable Result Sets


– to insert column values into the insert row. An updatable ResultSet object
has a special row associated with it that serves as a staging area for building
a row to be inserted
– The following code fragment moves the cursor to the insert row, builds a
three-column row, and inserts it into rs and into the data source table using
the method insertRow

– rs.moveToInsertRow(); // moves cursor to the insert row


rs.updateInt("EmployeeID", 1001);
rs.updateString("Name", "Divad Walker");
rs.updateString("Office", "HQ101");
rs.insertRow();
rs.moveToCurrentRow();
ADVANCED JDBC FEATURES

• Updateable Result Sets


– to delete a row. The following code fragment moves to the first row of the
ResultSet object rs and then uses the method deleteRow to delete the data
source table from which rs was derived

– rs.first(); // moves cursor to the deleting row


rs.deleteRow();
– Canceling Updates
• Rs.cancelRowUpdates();
ADVANCED JDBC FEATURES

• Batch Updates
– JDBC batch update is a collectively called when a group of SQL statements
are executed simultaneously to a database as a single unit
– The batch is sent to the database in a single request using connection object
– The advantage of batch is to reduce the network calls between the front end
application and its database rather than executing single SQL statement

– con.setAutoCommit(false) : This method return you the disable auto


commit.
– con.createStatement ( ) :
– st.addBatches (update ) : This is used to add the values of the parameter in
the database. This method return you the modify value in the database using
update query in the sql command. The method also shows the number of
rows affected in a table
ADVANCED JDBC FEATURES

• Batch Updates
– executeQuery ( ) : This method is used to retrieve the records from the
database using select query
– rs.next ( ) : This method return you the next successive value in the element
series

• st = con.createStatement();
st.addBatch("update person set cname='Ajay' where id='1'");
st.addBatch("update person set cname='Komal' where id='2'");
st.addBatch("update person set cname='Santosh' where id='3'");
st.executeBatch();
ADVANCED JDBC FEATURES

• Advanced Data Types


– Java Object Types
– SQL3 Types
– SQL BLOBs and CLOBs
• Character Large Object
• Binary Large Objects
• BLOB: Holds binary large objects. Mapped to the java.sql.Blob type.
• CLOB: Contains character large objects. Mapped to the java.sql.Clob
type.
– SQL Arrays
• ARRAY: Can store values of a specified type. Mapped to the
java.sql.Array type.
– SQL Structures
– SQL Distinct Types
– Custom Types
ADVANCED JDBC FEATURES

• Advanced Data Types


getXXX setXXX updateXXX
SQL3 type
method method method
BLOB getBlob setBlob updateBlob
CLOB getClob setClob updateClob
ARRAY getArray setArray updateArray
Structured
getObject setObject updateObject
type
REF
(structured getRef setRef updateRef
type)
ADVANCED JDBC FEATURES

• Row Sets
– JDBC RowSet is an interface of javax.sql.rowset interface
– This interface is wrapper around a ResultSet object that makes
possible to use resultSet as java beans object
– It can be one bean that makes available for composing of an
application
– Because a it continually maintain a connection JDBC connection to
the database
– Another advantage of JDBC RowSet is that it is used to makes
ResultSet object scrollable and updateable
– By default all the RowSet object are scrollable and updateable
ADVANCED JDBC FEATURES
• Row Sets
– import javax.sql.rowset.JdbcRowSet;
– JdbcRowSet jdbcRowSet =
new JdbcRowSetImpl(connection);

jdbcRowSet.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
String queryString = "SELECT * FROM student";
jdbcRowSet.setCommand(queryString);
jdbcRowSet.execute();

while (jdbcRowSet.next()) {
// Generating cursor Moved event
System.out.println("Roll No- " + jdbcRowSet.getString(1));
System.out.println("name- " + jdbcRowSet.getString(2));
}
ADVANCED JDBC FEATURES

• Stored Procedures
– A stored procedure is a subroutine available to applications that
access a relational database system. A stored procedure (sometimes
called a proc, sproc, StoPro, StoredProc, or SP) is actually stored in
the database data dictionary
– Stored procedures are precompiled database queries that improve
the security, efficiency and usability of database client/server
applications
– Developers specify a stored procedure in terms of input and output
variables
– They then compile the code on the database platform and make it
available to aplication developers for use in other environments,
such as web applications
– All of the major database platforms, including Oracle, SQL Server and
MySQL support stored procedures
ADVANCED JDBC FEATURES

• Stored Procedures
– CREATE PROCEDURE sp_GetInventory
@location varchar(10)
AS
SELECT Product, Quantity
FROM Inventory
WHERE Warehouse = @location

– EXECUTE sp_GetInventory 'FL'


ADVANCED JDBC FEATURES

• Benefits of Stored Procedures


– Precompiled execution
• SQL Server compiles each stored procedure once and then reutilizes the
execution plan. This results in tremendous performance boosts when
stored procedures are called repeatedly.
– Reduced client/server traffic
• If network bandwidth is a concern in your environment, you'll be happy
to learn that stored procedures can reduce long SQL queries to a single
line that is transmitted over the wire
– Efficient reuse of code and programming abstraction
• Stored procedures can be used by multiple users and client programs. If
you utilize them in a planned manner, you'll find the development cycle
takes less time
– Enhanced security controls
• You can grant users permission to execute a stored procedure
independently of underlying table permissions
ADVANCED JDBC FEATURES

• Database Naming

– The Java Naming and Directory Interface(JNDI) is a Java extension


and set of APIs that are part of the J2ee used to provide a standard
interface to naming and directory services

– Naming services provide a mechanism for binding human readable


names to object and resolving objects to name
ADVANCED JDBC FEATURES

import java.sql.*;
import javax.naming.*;
import javax.sql.*;
final class JDBCCONDATASRC {
String DATASOURCE_CONTEXT = "java:comp/env/jdbc/blah";
Connection result = null;
try {
Context initialContext = new InitialContext();
DataSource datasource = (DataSource)
initialContext.lookup(DATASOURCE_CONTEXT);
result = datasource.getConnection();
} catch (NamingException ex) {
log("Cannot get connection: " + ex);
} catch (SQLException ex) {
log("Cannot get connection: " + ex);
}
}
ADVANCED JDBC FEATURES

• Connection Pools
– Connection pooling is a technique of creating and managing a pool of
connections that are ready for use by any thread that needs them.

– This technique of "pooling" connections is based on the fact that


most applications only need a thread to have access to a JDBC
connection when they are actively processing a transaction, which
usually take only milliseconds to complete.

– When not processing a transaction, the connection would otherwise


sit idle. Instead, connection pooling allows the idle connection to be
used by some other thread to do useful work
ADVANCED JDBC FEATURES

• Benefits are there to Connection Pooling


– Reduced connection creation time
• While this is not usually an issue with the quick connection setup that
MySQL offers compared to other databases, creating connections still
has networking and JDBC driver overhead that will be avoided if
connections are "recycled."
– Simplified programming model
• When using connection pooling, each individual thread can act as
though it has created its own JDBC connection, allowing you to use
straight-forward JDBC programming techniques.
– Controlled resource usage
• If you don't use connection pooling, and instead create a new
connection every time a thread needs one, your application's resource
usage can be quite wasteful and lead to unpredictable behavior under
load.
ADVANCED JDBC FEATURES

• How Do I Implement Connection Pooling

– <data-source name="MySqlDS" location="jdbc/MySqlPooledDS"


class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"
max-connections="100" min-connections="5" inactivity-timeout="200" wait-
timeout="10" username="USERNAME" password="PASSWORD"
url="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEnco
ding=Cp1251" />
ADVANCED JDBC FEATURES

• Distributed Transaction
– A distributed transaction is a transaction that updates data on two or
more networked computer systems
– Distributed transactions extend the benefits of transactions to
applications that must update distributed data
– Implementing robust distributed applications is difficult because
these applications are subject to multiple failures, including failure of
the client, the server, and the network connection between the client
and server
– In the absence of distributed transactions, the application program
itself must detect and recover from these failures.
ADVANCED JDBC FEATURES

• Distributed Transaction
– two-phase commit algorithm
– local transaction manager
– Resource managers manage persistent or durable data
– global commit coordinator
END OF UNIT-1

Вам также может понравиться