Java HQL(hibernate) 时间戳范围匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2864925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HQL(hibernate) timestamp range match
提问by Saky
I need to write a query to get an object between a range of time, currently the query looks like this:
我需要编写一个查询来获取一个时间范围内的对象,目前查询如下所示:
Timestamp from = ...
Timestamp to = ...
getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString());
However, this doesnot work for obvious reasons. How can I format the timestamp to be acceptable by the query.
但是,由于显而易见的原因,这不起作用。如何格式化查询可接受的时间戳。
org.springframework.orm.hibernate3.HibernateQueryException:意外标记:16 靠近第 1 行,第 123 列 [来自 Person ml,其中 ml.lastModifiedOn>=2010-02-12 16:00:21.292 和 m1.lastModifiedOn采纳答案by Pascal Thivent
You're missing single quotes in your current query. The following should work:
您当前的查询中缺少单引号。以下应该工作:
from Person ml where ml.lastModifiedOn
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292'
Note that I don't know why you're not passing Date
instances to the following query:
请注意,我不知道您为什么不将Date
实例传递给以下查询:
from Person ml where ml.lastModifiedOn between :from and :to
Are you using java.sql.Timestamp
here? If yes, you shouldn't.
你java.sql.Timestamp
在这里用吗?如果是,你不应该。
回答by Bozho
You can simply pass a long
(from.getTime()
) in the comparison, if it is represented as long in the DB.
您可以简单地在比较中传递long
( from.getTime()
),如果它在 DB 中表示为 long。
Otherwise you can use these functiomns: second(...), minute(...), hour(...), day(...), month(...), and year(...)
否则,您可以使用这些功能: second(...), minute(...), hour(...), day(...), month(...), and year(...)
回答by limc
How about something like this?
这样的事情怎么样?
String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?";
Date from = ...;
Date to = ...;
getHibernateTemplate().find(sql, new Object[] {from,to});
回答by Shervin Asgari
If you want to query for something between you can do the following:
如果要查询之间的内容,可以执行以下操作:
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();
}
You might need to change TemporalType.DATE
to whatever you are using
您可能需要更改TemporalType.DATE
为您正在使用的任何内容