The following is an example of the Dynamic query remote client with added explanation.
import com.ibm.websphere.ejbquery.QueryHome; import com.ibm.websphere.ejbquery.Query; import com.ibm.websphere.ejbquery.QueryIterator; import com.ibm.websphere.ejbquery.IQueryTuple; import com.ibm.websphere.ejbquery.QueryException; try { String query = "select e.name as name , object(e) as emp from EmpBean e where e.salary < 50000"; InitialContext ic = new InitialContext(); Object obj = ic.lookup("com/ibm/websphere/ejbquery/Query"); QueryHome qh = ( QueryHome) javax.rmi.PortableRemoteObject.narrow( obj, QueryHome.class ); Query qb = qh.create();
You must specify a maximum size of the query result set. In this example 99 is used.
QueryIterator it = qb.executeQuery(query, null, null ,0, 99 );
The iterator contains a collection of IQueryTuple objects. Each tuple contains one value of name and one value of object(e) from the query. To display the contents of the query result, use the following code:
while (it.hasNext() ) { IQueryTuple tuple = (IQueryTuple) it.next(); System.out.print( it.getFieldName(1) ); String s = (String) tuple.getObject(1); System.out.println( s); System.out.println( it.getFieldName(2) ); Emp e = ( Emp) javax.rmi.PortableRemoteObject.narrow( tuple.getObject(2), Emp.class ); System.out.println( e.getPrimaryKey().toString()); }
The output from the program might look something like the following:
name Bob emp 1001 name Dave emp 298003 ...
Finally, catch and process any exceptions. An exception might occur because of a syntax error in the query statement or a run-time processing error. The following is an example that catches and processes these exceptions:
} catch (QueryException qe) { System.out.println("Query Exception "+ qe.getMessage() ); }