hibernate查询语句hql中的占位符?参数与命名参数:name设值方式搞混
先贴出异常
Struts has detected an unhandled exception:
Messages:
Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1
File: org/hibernate/engine/query/spi/ParameterMetadata.java
Stacktraces
org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1
代码:
//定义hql
String hql = "from Book book where " + "book.bookType like :queryArgs or " + "book .bookNum like :queryArgs or " + "book.bookName like :queryArgs or " + "book.bookAuthor like :queryArgs " + "order by book.bookType, book .bookNum, book.bookAuthor, book.bookName"; //dao中设值 Query query = sessionFactory.getCurrentSession().createQuery(hql); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); }
原因:
异常上说占位符索引越界(溢出),原因是我定义的hql中根本没有占位符“?”,我用的是命名参数,应该通过setString(paraName,paraValue)或者setParameter(paraName,paraValue)的方式来设值,我却用setParameter(int arg0, Object arg1)来设值,所以就报错了!
解决办法:
对于我这个,我通过吧:queryArgs全部替换成?的方式。