今天在用hibernate查询时,偶尔发现了一个问题:
org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1于是展开问题的解决方案搜索。
首先先解释一下,Hibernate 参数查询
第一种:
public User validate(String userName, String password) {
String hql = "from User where userName =:userName and password =:password";
User user = null;
Object[] values = {userName, password};
String[] paramNames = {"userName", "password"};
List<User> list = ht.findByNamedParam(hql, paramNames, values);
if (list.size()!=0){
user = list.get(0);
}
return user;
}
第二种:
public User validate(String userName, String password) {
String hql = "from User u where u.userName = ? and u.password = ?";
User user = null;
List<User> list = ht.find(hql, new Object[]{userName, password});
if (list.size()!=0){
user = list.get(0);
}
return user;
}
两种方法:find() 和 findByNameParam()
from User u ...... u可写可不写
总结:
当用"?"的时候,必须 ht.***("", new Object(*)); 否则会出现异常:这是因为一个占位符,只能给一个对象!!
org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1
当用"=:"的时候,必须定义参数 parameters,values。ht.***("", parameters, values);
参考博客:http://blog.csdn.net/learntech/article/details/8505099参考百度提问:http://zhidao.baidu.com/link?url=gnKMDNFKeKh3VMkT6IqJSkDtGJgUsOfQYkRV6Qi1YTRYDGA4M9h9Yz5UcbUuSU2AP4F0fBORjFlIdafRrUBzs_