2013-01-08 66 views
0

我试图与多个创建HQL查询其中相同休眠HQL查询

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

.setParameter paramteres(0,C [0]。价值)
.setParameter(1,C [1]。价值).LIST();的

,而不是做这个,我想创建一个查询,可以处理任何数量的paramters像

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

有查询看起来是正确的,但它说:“不能执行查询”

回答

1

一)为什么你放弃了使用像你一样的准备好的声明是固定大小的参数?

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

c)这个逗号是干什么的?它不应该是“和”还是“或”?

再评论你的答案

“一)使用多个PAMS而不是固定大小”

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),即使我有哪里使用上述代码失败只有一个PARAM !“ - ”

嗯,是的,即使你有一个参数,你仍然在最后添加逗号查询。这不是一个有效的格式

+0

a)使用多个pams而不是固定大小b)它应该是queryString c)即使我只有一个参数用于上述代码失败的地方! –

+0

@ user1827614看到我的编辑 – beder

+0

谢谢,这有助于! –