XQuery and the Oracle Database
The Oracle XQuery engine enables you to connect to the Oracle database and execute XQuery queries over the data stored in the database, the result sets of which are returned via an XQueryResultSetObject object. This capability is made possible through Oracle extensions that allow the execution of XQuery expressions over traditional database tables viewed as XML. Hence, the power of XQuery has been significantly enhanced with the Oracle implementation.
XQuery API for Java
OJXQI is the Java API for XQuery proposed by Oracle, and includes various extensions that Oracle supports for connecting to the database and binding variables, among other things. OJXQI provides an XqueryResultSet class that can be used to obtain the results of executing the XQuery.
To use OJXQI, you first need to construct a context. To do so, use the default constructor or pass in the connection information, prepare an XQuery or XQueryX statement by calling prepareXQuery() or prepareXQueryX(), respectively, bind any values to the return object of these calls, PreparedXQuery, execute the PreparedXQuery object, and then iterate over the XQueryResultSetObject. The following code fragment illustrates this:
XQueryContext ctx = new XQueryContext();
try {
// create a string from the file
Reader strm = new FileReader("exmpl1.xql");
// prepare the query
PreparedXQuery xq = ctx.prepareXQuery(strm);
// get a resultset
XQueryResultSet rset = xq.executeQuery();
while (rset.next()) {
// get result nodes
XMLNode node = rset.getNode();
System.out.println(" NODE "+ node.getNodeName());
node.print(System.out);
}
}
catch (Exception e) {
// do something..
}
A number of Oracle enhancements were made to support embedding SQL inside XQuery queries, to support bind variables so that the XQuery query is not re-executed, and to support XMLType.
Querying XML in the Database
Invoking the methods defined in OJXQI in a Java program enables you to query the database using XQuery expressions and operators. For example, the following XQuery will return the results of all the names and titles from an author table:
FOR $i IN sqlquery("select * from booklist.author"/ROW)
RETURN
$i/NAME,
$i/TITLE
The code to convert that to a Java program would look something like this:
// get the connection
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.
getConnection("jdbc:oracle:@", "scott", "tiger");
// create the context using that connection
XqueryContext ctx = new XQueryContext(conn);
// create a string from the file
Reader strm = new StringReader("For $i IN sqlquery(\"select * from
booklist.author\"), "+ " RETURN $i/NAME, $i/TITLE");
// prepare the query
PreparedXQuery xq = ctx.prepareXQuery(strm);
// get a result set
XqueryResultSet rset = xq.executeQuery();
while (rset.next()) {
XMLNode node = rset.getNode();
System.out.println(" NODE "+ node.getNodeName());
Node.print(System.out);
}