Hibernate Connection Pooling
In general, in Database related applications, if we want to perform database operations first we have to create connection object before database operations then we have to destroy connection object after the database operations. If we use this approach in database related applications then application performance will be reduced, because, Creating connection object and destroying Connection objects are two expensive processes.
In the above context, to improve application performance we have to avoid Connection object creation and Destruction processes every time, for this, we have to use Connection Pooling.
In Connection Pooling, first, we will create a pool object with a set of Connection objects at application loading time , then, we get Connection object from Pool when we want to perform database operations, after the database operations we will send Connection object back to Pool object with out destroying Connection object.
To provide Connection pooling in JDBC applications we have to use the following steps.
1. Create DataSource object
DataSource is an object , it able to manage all JDBC parameters inorder to create Connection objects and it able to manage Pool objects with Connection objects. In JDBC, to represent DataSource object, JDBC has provided a predefined interface in the form of javax.sql.DataSource and its implementations are provided by database vendors.
E.g:
OracleDataSource provided by Oracle.
MySQLDataSource provided my MySQL.
OracleDataSource ds = new OracleDataSource();
2. Set JDBC Parameters to create Connection objects in POOL
In DataSource, to create Connection objects in POOL , we have to provide Driver URL, Database User Name and Database password, etc for this, we have to use the following methods.
public void setURL(String driverURL) public void setUser(String dbUserName) public void setPassword(String password)
E.g
ds.setURL("jdbc:oracle:thin:@localhost:1521:xe"); ds.setUser("system"); ds.setPassword("ashok");
3. Get Connection Object from DataSource
To get Connection object from DataSource we have to use the following method.
public Connection getConnection()
E.g
Connection con = ds.getConnection();
Note
Perform Database operations with the Connection object.
4. Close Connection object
public void close()
E.g
con.close();
Note
When we access close() on Connection object which we get from Pool , then, Connection object will not be destroyed, where Connection object will be send back to Pool object.