Search This Blog

Friday 31 March 2017

JDBC - The Steps

JDBC : The Steps

In this article we are highlighting the steps to connect and process data in JDBC. For this article we are using Oracle Database. For other databases the drivers will vary but the steps will remain the same.
The steps involved in the process of connecting to a database and executing a query are as follows:
·         Load and register the JDBC driver.
·         Open a connection to the database.
·         Create a statement object to perform a query.
·         Execute the statement object and return a query resultset.
·         Process the resultset.
·         Close the resultset and statement objects.
·         Close the connection.

Load and Register the JDBC Driver
The first step is to establish a communication between the JDBC program and the database. This is done by using the static registerDriver() method of the DriverManager class of the JDBC API.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

Alternatively, we can use the forName() method of the java.lang.Class class can be used to load and register the JDBC driver:
Class.forName("oracle.jdbc.driver.OracleDriver");

Connecting to a Database
Once the JDBC driver has been loaded and registered, a database connection needs be established. This is done by using the getConnection() method of the DriverManager class. A call to this method creates an object instance of the java.sql.Connection class. The getConnection() requires three input parameters, namely, a connect string, a username, and a password.
Connection conn = DriverManager.getConnection(URL, username, passwd);

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@training:1521:Oracle",
 "oratest", "oratest");


Querying the Database
Querying the database involves two steps:
·         Creating a statement object to perform a query
·         Executing the query and returning a resultset.

Creating a Statement Object
The next step is to instantiate objects that run the query against the database connected. This is done by the createStatement() method of the Connection object created above. A call to this method creates an object instance of the Statement
Statement stmt = conn.createStatement();

Executing the Query and Returning a ResultSet
Once a Statement object has been constructed, the next step is to execute the query. This is done by using the executeQuery() method of the Statement object. A call to this method takes as parameter a SQL SELECT statement and returns a JDBC ResultSet object.
ResultSet rset = stmt.executeQuery
      ("SELECT empno, ename, sal, deptno FROM emp ");

Processing the Results of a Database Query That Returns Multiple Rows
Once the query has been executed, there are two steps to be carried out:
After the query execution we need to perform 2 things
·         Process the output resultset to fetch the rows
·         Retrievethe column values of the current row
The first step is using the next() method of the ResultSet object. A call to next() is executed in a loop to fetch the rows one row at a time, with each call to next() advancing the control to the next available row.
The second step is to fetch the values in the columnsby using the getXXX() methods of the JDBC rset object. Here getXXX() corresponds to the getInt(), getString() etc with XXX being replaced by a Java datatype.
String str;
while (rset.next())
 {
 str = rset.getInt(1)+ " "+ rset.getString(2)+ "
         "+rset.getFloat(3)+ " "rset.getInt(4)+ "\n";
 }

Here 1, 2, 3, and 4 in rset.getInt(), rset.getString(), getFloat(), and getInt() respectively denote the position of the columns in the SELECT statement, that is, the first column empno, second column ename, third column sal, and fourth column deptno of the SELECT statement respectively.
The parameters for the getXXX() methods can be specified by position of the corresponding columns as numbers 1, 2, and so on, or by directly specifying the column names enclosed in double quotes, as getString("ename") and so on, or a combination of both.
Closing the ResultSet and Statement
Once the ResultSet and Statement objects have been used, they must be closed.
rset.close();
stmt.close();

Closing the Connection
The last step is to close the database connection which is done by a call to the close() method.
conn.close();

Here is a complete example of JDBC Select using Type 4 driver and Oracle Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC01 {
public static void main(String[] args) {
                try {
                                                                Class.forName("oracle.jdbc.OracleDriver");
                } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                }
                try {
                               
Connection con =DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
                                Statement s=con.createStatement();
                                String query01="select * from emp";
                                ResultSet rs=s.executeQuery(query01);
                                while(rs.next()){
                System.out.println(rs.getInt("empno")+"    "+rs.getString("ename")+"   "+rs.getDouble("sal"));          
                                }

                } catch (SQLException e) {
                                e.printStackTrace();
                }
}
}



Wednesday 29 March 2017

JDBC Drivers

JDBC Drivers

A JDBC driver is a software component which enables a Java application to interact with a database. To connect with individual databases, JDBC requires drivers for each database. The JDBC driver felicitates connection to the database and implements the mechanism for transferring the query and result between client and database.

There are 4 (four) types of JDBC drivers.

1.    JDBC-ODBC bridge 
2.    Native-API driver 
3.    Network-Protocol driver (Middleware driver) 
4.    Database-Protocol driver (Pure Java driver) or thin driver.

Type 1 driver – JDBC-ODBC bridge

The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that uses the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls.

Type 1 driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the underlying operating system the JVM is running on. ODBC must be installed on the computer having the driver and the database must support an ODBC driver. The use of this driver is discouraged. Any application using a type 1 driver is non-portable.
Sun (now Oracle) provided a JDBC-ODBC Bridge driver: sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.

Advantages
·         Any database for which an ODBC driver is installed can be accessed, and data can be retrieved.
Disadvantages 
·         Performance overhead since the calls have to go through the JDBC bridge to the ODBC driver, then to the native database connectivity interface. 
·         The ODBC driver needs to be installed on the client machine.
·         Not suitable for applets, because the ODBC driver needs to be installed on the client.
·         Specific ODBC drivers are not always available on all platforms; hence, portability of this driver is limited.
·         No support from JDK 1.8 (Java 8) onwards.

Type 2 driver – Native-API drive

The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.
Advantages
·         As there is no implementation of JDBC-ODBC bridge, it may be considerably faster than a Type 1 driver.
Disadvantages
·         The vendor client library needs to be installed on the client machine.
·         Not all databases have a client-side library.
·         This driver is platform dependent.
·         This driver supports all Java applications except applets.

Type 3 driver – Network-Protocol driver (middleware driver)

The JDBC type 3 driver, also known as the Pure Java driver for database middleware, is a database driver implementation which makes use of a middle tier between the calling program and the database.
The middle-tier (application server) converts JDBC calls directly or indirectly into a vendor-specific database protocol. The type 3 driver is written entirely in Java. The same client-side JDBC driver may be used for multiple databases.
It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care of by the middleware.  Also, making use of the middleware provides additional advantages of security and firewall access.
Advantages
·  Since the communication between client and the middleware server is database independent,  there is no need for the database vendor library on the client. The client need not be changed for a new database.
·  The middleware server can provide typical middleware services like caching (of connections, query results, etc.),  load balancing, logging, and auditing.
·         A single driver can handle any database, provided the middleware supports it.

Disadvantages
·         Requires database-specific coding to be done in the middle tier.
·        The middleware layer added may result in additional latency, but is typically overcome by using better middleware services.

Type 4 driver – Database-Protocol driver (Pure Java driver)

The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol. Type 4 drivers are platform independent as they are written in Java. They install inside the Java Virtual Machine of the client. This provides better performance as it does not have the overhead of conversion of calls into ODBC or database API calls.
As the database protocol is vendor specific, the JDBC client requires separate drivers, usually vendor supplied, to connect to different types of databases.
Advantages
·         Completely implemented in Java to achieve platform independence.
·        These drivers don't translate the requests into an intermediary format.
·  The client application connects directly to the database server. No translation or middleware layers are used, improving performance.
·   The JVM can manage all aspects of the application-to-database connection; this can facilitate debugging.
Disadvantages
·         Drivers are database specific, as different database vendors use widely different network protocols.

Monday 27 March 2017

Java Database Connectivity

Java Database Connectivity

Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.

Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which allows to connect and execute query with the database. JDBC is a part of the Java Standard Edition platform. JDBC provides methods to query and update data in a database, and is oriented towards relational databases.

The JDBC classes are contained in the Java package java.sql and javax.sql.

The latest version is JDBC 4.2, and is included in Java SE 8.

JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections.

JDBC connections support creating and executing statements. These are SQL's CREATE, INSERT, UPDATE and DELETE statements, or they may be SELECT statement to query the database.
Also we can execute the stored procedures available in the database through a JDBC connection.
In order to execute queries in databases JDBC uses statements using one of the following interfaces:

·         Statement – the statement is sent to the database server each and every time.
·         PreparedStatement – the statement is cached and then the execution path is pre-determined on the database server allowing it to be executed multiple times in an efficient manner.
·         CallableStatement – used for executing stored procedures on the database.


SELECT Query statements return a JDBC row result set. The row result set is used to iterate over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set.

Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database.

Java Database Connectivity



Thursday 23 March 2017

Session Bean

Session Bean


session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. The session bean performs work for its client, by executing business tasks inside the server.
A session bean is not persistent.

Types of Session Beans
Session beans are of three types: 
·         Stateful 
·         Stateless 
·         Singleton.

Stateful Session Beans

A stateful session bean is a type of enterprise bean which preserve the conversational state with client. A stateful session bean as per its name keeps associated client state in its instance variables. EJB Container creates a separate stateful session bean to process client's each request. As soon as request scope is over, statelful session bean is destroyed.
The state of an object is the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client/bean session.
A session bean is not shared; it can have only one client. When the client terminates, its session bean terminates and is no longer associated with the client.
The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears.
Stateful session beans are appropriate in any of the following conditions.
·         The bean’s state represents the interaction between the bean and a specific client.
·         The bean needs to hold information about the client across method invocations.
·         The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
·         Behind the scenes, the bean manages the work flow of several enterprise beans.

Stateless Session Beans

A stateless session bean is a type of enterprise bean which is normally used to do independent operations. A stateless session bean does not have any associated client state, but it may preserve its instance state. EJB Container normally creates a pool of few stateless bean's objects and use these objects to process client's request.
stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained.
Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.
A stateless session bean can implement a web service, but a stateful session bean cannot.
Stateless session bean are appropriate in following circumstances
·         The bean’s state has no data for a specific client.
·         In a single method invocation, the bean performs a generic task for all clients.
·         The bean implements a web service.

Singleton Session Beans
singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients.
Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application.
Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns.
Applications that use a singleton session bean may specify that the singleton should be instantiated upon application startup, which allows the singleton to perform initialization tasks for the application. The singleton may perform cleanup tasks on application shutdown as well, because the singleton will operate throughout the lifecycle of the application.
Singleton session beans are appropriate in the following circumstances.
·         State needs to be shared across the application.
·         A single enterprise bean needs to be accessed by multiple threads concurrently.
·         The application needs an enterprise bean to perform tasks upon application startup and shutdown.
·         The bean implements a web service.


Tuesday 21 March 2017

Enterprise Beans

Enterprise Beans


Enterprise beans are Java EE components that implement Enterprise JavaBeans (EJB) technology. Enterprise beans run in the EJB container. The EJB container provides system-level services, such as transactions and security, to its enterprise beans

What Is an Enterprise Bean?
An enterprise bean is a server-side component that encapsulates the business logic of an application. The business logic is the code that fulfils the purpose of the application.
For Example :
In an ecommerce site the enterprise beans might implement the business logic in methods called checkOut and orderProduct. By invoking these methods, clients can access the services provided by the application.

Benefits of Enterprise Beans
Enterprise beans simplify the development of large, distributed applications.
  • The EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container, rather than the bean developer, is responsible for system-level services, such as transaction management and security authorization.
  • The beans contain the application’s business logic, the client developer can focus on the presentation of the client. The client developer does not have to code the routines that implement business rules or access databases. As a result, the clients are thinner, a benefit that is particularly important for clients that run on small devices.
  • Enterprise beans are portable components, the application assembler can build new applications from existing beans. Provided that they use the standard APIs, these applications can run on any compliant Java EE server.


When to Use Enterprise Beans
  • The application must be scalable.
  • Transactions must ensure data integrity. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects.
  • The application will have a variety of clients. 


There are two types of enterprise beans.
  • Session Beans : Performs a task for a client; optionally, may implement a web service
  • Message-driven Beans : Acts as a listener for a particular messaging type, such as the Java Message Service API

Saturday 18 March 2017

Prototype Design Pattern in Java

Prototype Design Pattern in Java

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Motivation
When we talk about object creation there is a better way to have new objects. If the cost of creating a new object is large and creation is resource intensive, we clone the object. Prototyping allows an object to create customized objects without knowing their class or any details of how to create them. This pattern involves implementing a prototype interface which tells to create a clone of the current object. 
The best example to understand Prototype Patter is, the mitotic division of a cell — resulting in two identical cells —that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.

Applicability
Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; and
·         When the classes to instantiate are specified at run-time.
·         To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
·         When instances of a class can have one of only a few different combinations of state.

Consequences
The Prototype pattern has several benefits:
·         Adding and removing products at run-time.
·         Specifying new objects by varying values.
·         Specifying new objects by varying structure.
·         Reduced subclassing.
·         Configuring an application with classes dynamically.



Implementation
import java.util.ArrayList;
import java.util.List;

public class Employees implements Cloneable{

      private List<String> empList;
     
      public Employees(){
            empList = new ArrayList<String>();
      }
     
      public Employees(List<String> list){
            this.empList=list;
      }
      public void loadData(){
//This part can be used to read data from the Database and add to List
            empList.add("Ravi");
            empList.add("Ajay");
            empList.add("Sumit");
            empList.add("Pooja");
      }
     
      public List<String> getEmpList() {
            return empList;
      }

      @Override
      public Object clone() throws CloneNotSupportedException{
                  List<String> temp = new ArrayList<String>();
                  for(String s : this.getEmpList()){
                        temp.add(s);
                  }
                  return new Employees(temp);
      }
     
}

import java.util.List;

public class TestPrototypePattern {

      public static void main(String[] args) throws CloneNotSupportedException {
            Employees emps = new Employees();
            emps.loadData();
           
            //Use the clone method to get the Employee object
            Employees empsNew = (Employees) emps.clone();
            Employees empsNew1 = (Employees) emps.clone();
            List<String> list = empsNew.getEmpList();
            list.add("Simran");
            List<String> list1 = empsNew1.getEmpList();
            list1.remove("Sumit");
           
      System.out.println("Existing Employee List: "+emps.getEmpList());
System.out.println("Employee List after adding an Employee : "+list);
System.out.println("Employee List after removing an Employee : "+list1);
      }
}

Output :
Existing Employee List: [Ravi, Ajay, Sumit, Pooja]
Employee List after adding an Employee : [Ravi, Ajay, Sumit, Pooja, Simran]
Employee List after removing an Employee : [Ravi, Ajay, Pooja]