日期:2014-05-17  浏览次数:20772 次

S2SH中的日期查询
本人是个新手,刚学习完ssh,做个实习小项目,遇到点问题一直想不明白,请各位高手帮忙指点。谢谢!
我想要从信息表中按 年和月 取出当月的所有记录,信息表中的字段是 年月日 格式的
代码如下;一直出错,
String queryString = "from WorkInfo w where w.createDate in (";
  for(int i=0; i<dates.length; i++) { //dates是当前月份每一天组成的日期类型数组
if(i == dates.length-1) {
queryString += dates[i] + ")";
  }else {
queryString += dates[i] + ",";
  }
  }
List list = getHibernateTemplate().find(queryString);

比如输入2012 年 7 月 出现下面的错误信息
org.springframework.orm.hibernate3.HibernateQueryException:
Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 00 near line 1, column 94 [from com.cn.entity.WorkInfo w where w.createDate in (2012-07-01 00:00:00.0,2012-07-02 00:00:00.0,2012-07-03 00:00:00.0,2012-07-04 00:00:00.0,2012-07-05 00:00:00.0,2012-07-06 00:00:00.0,2012-07-07 00:00:00.0,2012-07-08 00:00:00.0,2012-07-09 00:00:00.0,2012-07-10 00:00:00.0,2012-07-11 00:00:00.0,2012-07-12 00:00:00.0,2012-07-13 00:00:00.0,2012-07-14 00:00:00.0,2012-07-15 00:00:00.0,2012-07-16 00:00:00.0,2012-07-17 00:00:00.0,2012-07-18 00:00:00.0,2012-07-19 00:00:00.0,2012-07-20 00:00:00.0,2012-07-21 00:00:00.0,2012-07-22 00:00:00.0,2012-07-23 00:00:00.0,2012-07-24 00:00:00.0,2012-07-25 00:00:00.0,2012-07-26 00:00:00.0,2012-07-27 00:00:00.0,2012-07-28 00:00:00.0,2012-07-29 00:00:00.0,2012-07-30 00:00:00.0,2012-07-31 00:00:00.0)]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1651)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:914)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
... 29 more

------解决方案--------------------
String hql = "from WorkInfo w where w.createDate between '"+dates[0]+"' and '"+dates[dates.length-1]+"'";

List list = getHibernateTemplate().find(queryString);

如果是我的話,也許會這樣寫,LZ可以試試的
------解决方案--------------------
LZ的那個錯誤也許是因為日期格式沒有加引號的關系,日期和字符串類型的都要加引號的!沒去測試,憑感覺猜的