Database Mechanics in NetBeans

This web presentation covers database mechanics in NetBeans for using GlassFish with the Apache Derby database. It describes 5 kinds of operations, demonstrated on the database example application from CoreJSF Chapter 6.


Web applications usually need access to a database. This access is provided by application servers such as GlassFish. NetBeans works with the GlassFish application server to provide support for creating JDBC resources that can be accessed by JSF applications.

A JDBC resource is a database resource that can be registered with an Java-based application server for access by a web application program. It is an object that implements the javax.sql.DataSource interface. Its getConnection() method returns a java.sql.Connection object. This object has methods for sending SQL queries to the database behind the resource.

Most implementations of the java.sql.Connection interface set up pools of connections to a database. A connection pool supports multiple clients connecting to a server. Each client gets its connections from the pool and returns them when it is done by closing the connection. Creating new connections takes significantly longer than fetching one from a pool, so this is a performance optimization.

Managed beans in JSF applications can retrieve a JDBC resource object by declaring a DataSource variable with a @Resource annotation as in the following:

   private DataSource ds;

A JSF application must use the resource responsibly. It does this by using the following code pattern for database operations.

      Connection conn = ds.getConnection();
      try {
         // JDBC statements to execute SQL through conn
      } finally {

Invoking getConnection() retrieves a connection from the pool. Sending the connection a close() message returns it to the pool. Putting the close() invocation in the finally clause ensures that the connection is returned to the pool even if exceptions are thrown.