JCR 2.0 introduces a new API for programmatically constructing a query. This API allows the client to construct the lower-level objects for each part of the query, and is a great fit for applications that would otherwise need to dynamically generate query expressions using fairly complicated string manipulation.
Using this API is a matter of getting the QueryObjectModelFactory from the session's QueryManager, and using the factory to create the various components, starting with the lowest-level components. Then these lower-level components can be passed to other factory methods to create the higher-level components, and so on, until finally the createQuery(...) method is called to return the QueryObjectModel.
|Although the JCR-SQL2 and Query Object Model API construct queries in very different ways, executing queries for the two languages is done in nearly the same way. The only difference is that a JCR-SQL2 query expression must be parsed into an abstract syntax tree (AST), whereas with the Query Object Model API your application is programmatically creating objects that effectively are the AST. From that point on, however, all subsequent processing is done in an identical manner for all the query languages.
However, please do not consider using the QOM API just to get a performance benefit. The JCR-SQL2 parser is very efficient, and your application code will be far easier to understand and maintain. Where possible, use JCR-SQL2 query expressions.
Here is a simple example that shows how this is done for the simple query "SELECT * FROM [nt:unstructured] AS unstructNodes":
Obviously this is a lot more code than would be required to just submit the fixed query expression, but the purpose of the example is to show how to use the Query Object Model API to build a query that you can easily understand. In fact, most Query Object Model queries will create the columns, orderings, and constraints using the QueryObjectModelFactory, whereas the example above just assumes all of the columns, no orderings, and no constraints.
Once your application executes the QueryResult, processing the results is exactly the same as when using the JCR Query AP. This is because all of the query languages are represented internally and executed in exactly the same manner. For the sake of completion, here's the code to process the results by iterating over the nodes:
or iterating over the rows in the results: