I am learning how to work with Servlet api and trying to develop my first web application. And I have a problem with JDBC connection. I understand how I can connect to my DB, but I want to get connection from connection pool. I dont understand how I can work with it. Can you give me advice or link to example application to see how it works?
Asked
Active
Viewed 198 times
1 Answers
0
GenericObjectPool class can be used to create pool of arbitrary objects. You can create pool as below.
public DataSource setUpPool() throws Exception {
Class.forName(JDBC_DRIVER);
// Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object!
gPool = new GenericObjectPool();
gPool.setMaxActive(5);
// Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object!
ConnectionFactory cf = new DriverManagerConnectionFactory(JDBC_DB_URL, JDBC_USER, JDBC_PASS);
// Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality!
PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true);
return new PoolingDataSource(gPool);
}
Get connection from pool using above method:
ConnectionPool jdbcObj = new ConnectionPool();
Connection connObj = null;
DataSource dataSource = jdbcObj.setUpPool();
connObj = dataSource.getConnection();

heyitsvajid
- 1,023
- 1
- 10
- 19