使用 Hibernate HQL 執行 IN (:agentIds) 查詢時,若參數列表 ids 為空集合,直接呼叫 query.setParameterList("agentIds", ids) 會拋出異常。
StringBuffer buf = new StringBuffer();
if (!forObject) { buf.append("select count(*) "); }
buf.append("from Agent agent where 1=1 ");
String gradeId = (String) conditions.get("gradeId");
if (gradeId != null && !gradeId.equals("")) {
buf.append(" and agent.gradeId=").append(gradeId);
}
buf.append(" and agent.agentId in (:agentIds) ");
Query query = sess.createQuery(buf.toString());
List ids = CommisionInfoDelegateExt.findAgentIdList(conditions);
System.out.println("ids.length=" + ids.size());
query.setParameterList("agentIds", ids); // ids 為空時拋異常
在列表塞入一個絕不存在的 ID(如 "-1"):
if (ids.isEmpty()) ids.add("-1");
缺點:汙染查詢邏輯、潛在效能影響、非語意正確。
List ids = CommisionInfoDelegateExt.findAgentIdList(conditions);
StringBuffer buf = new StringBuffer();
if (!forObject) buf.append("select count(*) ");
buf.append("from Agent agent where 1=1 ");
String gradeId = (String) conditions.get("gradeId");
if (gradeId != null && !gradeId.equals("")) {
buf.append(" and agent.gradeId = :gradeId");
}
if (ids != null && !ids.isEmpty()) {
buf.append(" and agent.agentId in (:agentIds) ");
}
Query query = sess.createQuery(buf.toString());
if (gradeId != null && !gradeId.equals("")) {
query.setParameter("gradeId", gradeId);
}
if (ids != null && !ids.isEmpty()) {
query.setParameterList("agentIds", ids);
}
Criteria crit = sess.createCriteria(Agent.class);
if (gradeId != null && !gradeId.equals("")) {
crit.add(Restrictions.eq("gradeId", gradeId));
}
if (ids != null && !ids.isEmpty()) {
crit.add(Restrictions.in("agentId", ids));
}
// 若 ids 為空,不加入 in 條件,等同查詢全部(視業務而定)
List results = crit.list();
IN 子句。