Friday, July 17, 2009

A Java API for XQuery

A Basic Example
Here's a basic code example that uses XQJ to execute a query that illustrates a typical use. Note that error handling has been omitted for clarity.


// obtain an XQDataSource instance
XQDataSource xqds = (XQDataSource)
Class.forName("com.jsr225.xqj").newInstance();
// obtain a connection
XQConnection con = xqds.getConnection("usr", "passwd");

// prepare an XQuery Expression
String xqry = "for $i in fn:collection('dept') " +
"where $i/deptname = %dname return count($i/employees)";
XQPreparedExpression expr = con,preparedExpression(xqry);

// bind variable with value
expr.bindString(new Qname("dname"), "engineering");

// execute the XQuery Expression
XQResultSequence rs = expr.executeQuery();

// Consume results
while (rs.next())
{
System.out.printLn(rs.getInt());
}

// clean up resources
rs.close();
con.close();

In the preceding code, XQDataSource is an interface from which you obtain XQuery connections. You can create the initial implementation class for the XQDataSource interface via a typical data source instantiation mechanism, such as JNDI look up or an explicit class-loading method. This is similar to the design of JDBC's DataSource and Connection interfaces.

After obtaining an XQConnection, you execute the XQuery using either the XQExpression or XQPreparedExpression interfaces. You'd use XQExpression when you want to execute an XQuery expression once, and XQPreparedExpression when you want to prepare the XQuery expression once and execute it multiple times with different bind values, as illustrated in the preceding example. These two interfaces are similar to the concepts of Statement and PreparedStatement in JDBC, respectively.

An XQuery result is an instance of the XQuery data model. The XQResultSequence shown in the example provides a cursor-centric interface that allows users to iterate through each item in the result sequence. Users can obtain values from each item, either atomic values or XML nodes. This is similar to iterating through a JDBC result set.

After consuming the XQuery results, developers need to clean up the resources by calling the close() method on the XQResultSequence and XQConnection interfaces. Proper error-handling code for releasing resources is critical to avoid resource leakage. The framework implicitly closes items created from the sequence result when the sequence result is closed. Similarly, the sequence result is implicitly closed if the connection is closed.

0 comments: