Hibernate查询返回错误

时间:2011-01-26 15:17:22

标签: hibernate

我有以下hibernate查询 -

    events = (List<Event>)session.createQuery(
            "Event where eventName like " 
            + "\"" + event.getEventName() 
            + "\"" +
            " and startingDate >=   "
            + "\"" + 
            event.getStartingDate() 
            + "\" " +
            " and endingDate <=  " 
            + "\"" + 
            event.getEndingDate()
            + "\" "
            ).list();

但它返回错误 -

org.hibernate.QueryException:意外的char:'“'[事件,其中eventName如”test“和startingDate&gt; =”2011-01-19“和endingDate&lt; =”2011-01-31“]     在org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:227)     在org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:134)     在org.hibernate.engine.query.HQLQueryPlan。(HQLQueryPlan.java:101)     在org.hibernate.engine.query.HQLQueryPlan。(HQLQueryPlan.java:80)

似乎在说它不喜欢某个地方?

在我将日期字段添加到where子句之前,它一直运行良好。

由于

1 个答案:

答案 0 :(得分:2)

首先:您应该使用单引号char来分隔字符串。像这样:'字符串'。其次,不要通过连接字符串来构建查询。使用参数标记,如下所示:

Event where eventName like ? and startingDate >= ? and endingDate <= ?
Event where eventName like :name and startingDate >= :startDate and endingDate <= :endDate

然后,从setParameter()对象调用Query方法来设置参数。您可以使用位置参数(例如,“?位置0是'名称'”)或命名参数(“:名称是'名称'”)。请参阅Hibernate文档中的“绑定参数”部分:http://docs.jboss.org/hibernate/core/3.5/reference/en/html_single/#objectstate-querying-executing