2010-05-19 94 views
1

我需要编写一个查询来获得一定范围的时间之间的对象,目前查询是这样的:HQL(休眠)日期和时间范围内的比赛

Timestamp from = ... 
Timestamp to = ... 

getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString()); 

然而,对于这种不列入工作明显的原因。我该如何格式化时间戳才能被查询接受。

org.springframework.orm.hibernate3.HibernateQueryException:意外的标记:16附近线1,列123 [从人毫升其中ml.lastModifiedOn> = 2010-02-12 16:00:21.292和m1.lastModifiedOn
+0

试YYYY-MM-DD HH:MM:SS – Inv3r53 2010-05-19 11:27:47

+0

不起作用。 。 – Saky 2010-05-19 11:53:04

回答

3

您在当前查询中缺少单引号。下面应该工作:

from Person ml where ml.lastModifiedOn 
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292' 

请注意,我不知道为什么你不及格Date实例以下查询:

from Person ml where ml.lastModifiedOn between :from and :to 

是否使用java.sql.Timestamp在这里?如果是的话,你不应该。

+0

是的,我基本上在整个项目中使用时间戳,虽然这工作: 时间戳从= ..; 时间戳= =; DetachedCriteria criteria = DetachedCriteria.forClass(Person.class); criteria.add(限制之间(“lastModifiedOn”,from,to)); 列表 results = getHibernateTemplate()。findByCriteria(criteria); – Saky 2010-07-01 14:18:41

2

如果在DB中表示为long,则只需在比较中传递longfrom.getTime())即可。

否则,你可以使用这些functiomns:second(...), minute(...), hour(...), day(...), month(...), and year(...)

+1

在数据库中,它表示为DATETIME而不是很长。 我如何在整个日期时间匹配中使用这些函数? – Saky 2010-05-19 11:42:36

1

怎么这样呢?

String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?"; 
    Date from = ...; 
    Date to = ...; 

    getHibernateTemplate().find(sql, new Object[] {from,to}); 
+0

我试过了,我得到一个错误。 [错误] 13:58:03 PARSER-无效的路径:'m1.lastModifiedOn' [错误] 13:58:03 PARSER - :0:0:子树的意外结束 [错误] 13:58:03 PARSER - 二元运算符的左侧操作数为null org.springframework.orm.hibernate3.HibernateQueryException:无效路径:'m1.lastModifiedOn'[from it.Person ml where ml.lastModifiedOn> =?和m1.lastModifiedOn <=?];嵌套异常是org.hibernate.hql.ast.QuerySyntaxException:路径无效:'m1.lastModifiedOn'[from it.Person ml where ml.lastModifiedOn> =?和m1.lastModifiedOn <=?] ... 奇怪! – Saky 2010-06-04 13:29:44

0

如果您想查询的东西之间,你可以做到以下几点:

public List findPerson() { 
    Date from = ...; 
    Date to = ...; 
    return entityManager.createQuery(
    "SELECT p from Person p WHERE p.lastModifiedOn BETWEEN ?1 AND ?2") 
    .setParameter(1,from, TemporalType.DATE) 
    .setParameter(2,to, TemporalType.DATE).getResultList(); 
} 

您可能需要更改TemporalType.DATE,无论你正在使用