Sunday, August 05, 2007

Creating a Connection Pool Using NetBeans

In a previous blog entry, I outlined the steps to create a connection pool within Tomcat. As promised, here is the easy way to create a DataSource using NetBeans wizards. This assumes that you have already created a database connection. For more details, see my article on Accessing Databases from NetBeans. Assuming you have a web application project already open, here are the steps.

  1. Select File > New File.
  2. Under Categories, select Sun Resources.
  3. Under File Types, select JDBC Connection Pool. Click Next.
  4. You will now be asked to choose a database connection. Give your pool a name. Take note of this name as this will be the name used within your code. Since this article assumes you have already defined a database connection, select Extract from Existing Connection, then click Next.
  5. In the Add Connection Pool Properties dialog, the defaults should be ok, but double check to make sure that everything is in order.
  6. From here on, you can select Next to add optional properties, or you can just select Finish.

That's it. Now if you want to use your connection pool within your code, right-click on the source editor window, select Enterprise Resources > Use Database. Select the DataSource from the drop-down list. This will generate code similar to the following:

private DataSource getJdbcGrocerificDB() throws NamingException {
Context c = new InitialContext();
return (DataSource) c.lookup("java:comp/env/jdbc/yourPoolName");
}

You can use this method to acquire the DataSource, and once you have it, you can just use DataSource.getConnection() to acquire a Connection object from the connection pool.

No comments: