Windchill 高级查询之查询条件动态变化写法
本文主要陈述在高级搜索业务场景,定义后台查询方法时需要考虑:
- 查询条件支持动态扩展
- 定义高级查询时需要明确定义是否需要查出该对象的子类
- 查询方法是否需要忽略权限
- 查询方法尽量支持批量查询,减少数据库与服务器的交互
- 查询条件能命中索引的写在最后面,筛选结果集的放在where里面
- 尽量返回对象,调用的地方通过对象获取相关属性
举个栗子
public static List<WTPart> queryItemByNumberAndState(String ipNumber, String state)
throws WTPropertyVetoException, WTException {
List<WTPart> itemResult = new ArrayList<WTPart>();
if (!RemoteMethodServer.ServerFlag) {
try {
Class[] argType = { String.class, String.class };
Object[] arg = { ipNumber, state };
return (List) RemoteMethodServer.getDefault().invoke("queryItemByNumberAndState",
GPPtoSAPInfoHelper.class.getName(), null, argType, arg);
} catch (Exception e) {
//TODO
}
} else {
boolean isAccess = SessionServerHelper.manager.isAccessEnforced();
try {
if (isAccess) {
SessionServerHelper.manager.setAccessEnforced(false);
}
QuerySpec qs = new QuerySpec(WTPart.class);
qs.setAdvancedQueryEnabled(true);
qs.getFromClause().setAliasPrefix("A");
// 高级查询动态拼接SQL,第一句先写where 1=1 方便后面动态扩展写其他条件
qs.appendWhere(new SearchCondition(new ConstantExpression("1"), SearchCondition.EQUAL,
new ConstantExpression("1")));
if (StringUtils.isNotBlank(ipNumber)) {
qs.appendAnd();
qs.appendWhere(new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, ipNumber));
}
if (StringUtils.isNotBlank(state)) {
qs.appendAnd();
qs.appendWhere(new SearchCondition(WTPart.class, WTPart.STATE, SearchCondition.EQUAL,
state.toUpperCase().trim()));
} else {
qs.appendAnd();
qs.appendWhere(new SearchCondition(WTPart.class, WTPart.STATE, SearchCondition.EQUAL, "RELEASED"));
}
QueryResult qr = PersistenceHelper.manager.find(qs);
while (qr.hasMoreElements()) {
WTPart itemInfo = (WTPart) qr.nextElement();
itemResult.add(itemInfo);
}
} catch (WTException e) {
logger.error(e);
} finally {
SessionServerHelper.manager.setAccessEnforced(isAccess);
}
}
return itemResult;
}