HQL date query question
if I am expecting a Date object say for 2011-03-05
and I want to use HQL to pull everything in 2011-03, ignoring the day/05
开发者_开发问答something like where year(somecolumn) = year(datepassedin) and month(somecolumn) = month(datepassedin)
is it possible to do in HQL?
It seems to be pertty easy to do in SQL, but not in HQL
Well HQL has year and month expressions and you can feed it date objects just fine. So, just use a Query object as usual, nothing fancy or complicated.
I tried two different versions of this same query and in SQL Server, something like what you have where year(somecolumn)
was significantly slower (by almost an order of magnitude) than a bracketing query.
You have to create two dates, one at the beginning of the range, and one at the end. Say that you have a string:
val data = "2011-03-05"
Somewhere create a convenient const for parsing the value:
val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM")
And then:
val yearMonthString = data.substring(0, 7)
val fromValue = dateFormat.parse(yearMonthString)
val c: Calendar = Calendar.getInstance(iPutATimeZoneHere)
c.setTime(fromValue)
c.add(Calendar.MONTH, 1)
val toValue = c.getTime
In your query, you'll have where somecolumn >= :fromValue and somecolumn < :toValue
.
This code is written in Scala, but it uses standard Java libraries.
精彩评论