示例:将远程接口用于动态查询

使用远程接口运行动态 Enterprise JavaBeans (EJB) 查询时,您是对 Query 接口调用 executeQuery 方法。executeQuery 方法对该接口具有一个值为 REQUIRED 的事务属性;因此,您无需显式建立一个事务上下文即可运行查询。

用以下导入语句作为开头:

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;

接着,以字符串形式编写您的查询语句,如以下示例所示(该示例检索未付足工资员工的姓名和 EJB 引用):

String query = 
"select e.name as name , object(e) as emp from EmpBean e where e.salary < 50000"; 

通过从 QueryHome 类获取一个引用来创建 Query 对象。(这个类定义了 executeQuery 方法。)请注意,为简洁起见,以下示例对 Query 对象使用动态查询 JNDI 名称:

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();

随后,您必须为查询结果集指定一个最大大小,它在 QueryIterator 对象(随 Class QueryIterator 附带)中定义。随后,您必须为查询结果集指定一个最大大小,它在 QueryIterator 对象(随 QueryIterator API 包附带)中定义。该示例将结果集的最大大小设置为 99:

QueryIterator it = qb.executeQuery(query, null, null ,0, 99 );
迭代器包含一组 IQueryTuple 对象,它们是返回集合值的记录。根据示例查询语句中的条件,该方案中的每个元组包含一个 name 值和一个 object(e) 值。要显示该查询结果的内容,请使用以下代码:
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());
}
程序的输出可能类似于以下内容:
name Bob 
emp 1001
name Dave
emp 298003
...
最后,捕获并处理任何异常。运行时处理错误或查询语句中的语法错误可能导致出现异常。以下示例捕获并处理了这些异常:
} catch (QueryException qe) {
    System.out.println("Query Exception "+ qe.getMessage() );
}

为远程接口查询处理大型结果集

如果您计划使查询返回一个大型集合,那么可以选择对它进行编程,以返回多个更容易管理、更小的结果集合。在远程 executeQuery 方法中使用 skipRow 和 maxRow 参数以分块检索答案。例如:

int skipRow=0;
int maxRow=100;
QueryIterator it = null;
do {
		it = qb.executeQuery(query, null, null ,skipRow, maxRow );
	while (it.hasNext() ) {
	// display result 
		skipRow = skipRow + maxRow;
}
} while ( ! it.isComplete() ) ;

指示主题类型的图标 参考主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=xque_remoteclient
文件名:xque_remoteclient.html