The XQuery language is designed specifically for XML programming and data
integration, and programmers are more productive using XQuery for these tasks.
However, many enterprise applications are built on the Java platform, and often
require functionality not found in XQuery; for instance, many XML programs need
to use the Web Services functionality of J2EE. On the Java platform, XML is
accessed and manipulated as a DOM tree, a SAX stream, or as a StAX stream.
The XQuery API for Java, currently under development as JSR 225, lets
programmers have the best of both worlds, using XQuery for XML programming and
data integration, with full access to the J2SE and J2EE platforms. XQJ allows a
Java program to connect to XML data sources, prepare and issue XQueries, and
process the results as XML. This functionality is similar to that of JDBC® Java
API for SQL, but the query language for XQJ is XQuery.
This article shows how XQJ is used to issue XQueries and obtain results. Next,
it shows how XQJ can be used to query DOM trees, perform joins between XML and
relational sources, obtain results using StAX, and issue prepared XQueries
(similar to JDBC's prepared statements). Finally, we show four complete,
working XQJ programs, including one that uses StAX to handle output. These
programs are based on the Early Draft Review of JSR-225, released in May 2004.
Code examples were tested with DataDirect XQuery™ 1.0, which implements XQuery
Querying Relational Data to Create XML
Although XQuery is a native XML query language, it is often used to query XML
views of relational data to create XML results. Most Java programmers are
familiar with the JDBC API. This example shows the similarities between JDBC
and XQJ, using an XQJ connection to query a relational database and print out
the results to the standard output.
SQL/XML Views of the Tables
The examples in this article are based on financial stock data, with a set of
users and stock holdings for each user. DataDirect XQuery relational data using
the SQL/XML mappings defined by SQL:2003. Here's the SQL/XML description of the
USERS table (only a few rows are shown).
Here's the XML mapping of the HOLDINGS table, which contains the (fictional!)
stock holdings for each user. Again, only a few rows are shown.
Querying SQL/XML Views
For relational data, XQuery often is used as a reporting language, combining
data to display on a web page or for use in a web message. Here's an XQuery
that returns results that show the stocks held by each user.
for $u in collection("USERS")/USERS/row
for $h in collection("HOLDINGS")/HOLDINGS/row
where $h/USERID = $u/USERID
This query uses an XQuery function named collection() to address tables-the
collection() function accepts a string and returns a sequence of nodes. In this
sample query, we bind the variables $u and $h to the SQL/XML view of rows in
the USERS and HOLDINGS tables.