0

我正在尝试使用多个 where 参数创建 HQL 查询

result = sessionFactory.getCurrentSession().createQuery("from County where " + [0].property + "=?"+","+ c[1].property + "=?")

.setParameter(0, c[0].value)
.setParameter(1, c[1].value).list();

我没有这样做,而是尝试创建一个可以处理任意数量的参数的查询,例如

for(Params c:parms){`enter code here`
    queryString+= c.property +" = "+c.value+",";
    }
result = (State) sessionFactory.getCurrentSession()
                .createQuery("from County where " +queryString)
                .list().get(0);

那里的查询看起来正确,但它说“无法执行查询”

4

1 回答 1

1

a)你为什么放弃使用准备好的语句,就像你使用固定大小的参数一样?

b) 你为什么要归因c.property +" = "+c.value+",";于“结果”而不是 queryString?

c) 逗号对所述属性有何作用?不应该是“和”或“或”吗?

重新评论你的答案

"a) 使用多个 pam 而不是固定大小"

String whereClause = new String();
for (Params p : params) {
    if (whereClause.isEmpty())
        whereClause = " where ";
    else
        whereClause += " and ";
    whereClause += p.property + " = ? ";
}
Query query = sessionFactory.getCurrentSession().createQuery("from County " + whereClause);
for (int i = 0; i<params.size(); i++) {
    query.setParameter(i, params[i].value);
}
result = (State) query.list().get(0);

“c)即使我只有一个参数来说明使用上述代码失败的地方!-”

好吧,是的,即使您有一个参数,您仍然在查询末尾添加一个逗号。这不是有效的格式

于 2013-01-08T17:48:13.643 回答