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.
NetBeans needs to be connected to a database in order to execute SQL commands on or create a JDBC resource for that database.
SQL commands are often executed from NetBeans in order to create, populate, and modify database tables.
Connecting NetBeans to a database does not give JSF applications access to the database. JSF applications need a JDBC resource provided by the application server. If NetBeans has created a database it can work with a GlassFish application server to set up a JDBC resource for it.
To use a JDBC resource, a managed bean needs to inject it and then invoke JDBC operations on the injected resource.
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:
@Resource(name="jdbc/mydb") 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 { conn.close(); }
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.