package com.corejsf; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.annotation.Resource; import javax.inject.Named; // or import javax.faces.bean.ManagedBean; import javax.enterprise.context.RequestScoped; // or import javax.faces.bean.RequestScoped; import javax.sql.DataSource; import javax.sql.rowset.CachedRowSet; @Named // or @ManagedBean @RequestScoped public class CustomerBean { @Resource(name="jdbc/mydb") private DataSource ds; public ResultSet getAll() throws SQLException { Connection conn = ds.getConnection(); try { Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery("SELECT * FROM Customers"); // return ResultSupport.toResult(result); CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl(); // or use an implementation from your database vendor crs.populate(result); return crs; } finally { conn.close(); } } }
Accessing a JDBC resource requires injecting the resource. Then JDBC messages can be sent to the injected resource. The resource is injected with the following declaration:
@Resource(name="jdbc/mydb") private DataSource ds;
JDBC access begins by sending a getConnection() message to the injected resource variable. JDBC messages sent to the connection should be enclosed in a try…finally similar to the one below. The use of these JDBC methods is explained in Introduction to JDBC.
Connection conn = ds.getConnection(); try { Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery("SELECT * FROM Customers"); // return ResultSupport.toResult(result); CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl(); // or use an implementation from your database vendor crs.populate(result); return crs; } finally { conn.close(); }