Question

Hi I have trouble executing the following query in HQL:

Was it helpful?

Solution

This is a very dangerous approach to running queries. It's the sort of thing that creates SQL injection risks. Never concatenate values into SQL or HQL strings like that. Always use the PreparedStatement approach of using placeholders in the SQL/HQL string and setting the values programmatically. This way the driver (and Hibernate in the case of HQL) can do the correct thing with the SQL that gets generated. Of course here the value is a date and not a user-submitted string, but the principle still holds.

What you need to do is run a query more like

'select stuff from bar b where b.dateCreated = ?'

In HQL you can also use named parameters, and those are usually a lot easier to read and self-documenting, e.g.

'select stuff from bar b where b.dateCreated = :date'

Then set the value as part of the call, not with string concatenation.

The problem here is that the Java/Groovy toString value of a date is nothing at all like what the date format should be in SQL (or HQL). Luckily you don't need to know what that format should be, because the JDBC driver does.

So your query should be

def co = Bid.executeQuery(
   'select b.job from Bid b left join b.job j where j.dateCreated = :date',
   [date: fromDates[i])

Here I'm using the name date but that's arbitrary, is just has to match the key name in the map with values. You can also use SQL-style ? chars and a list of values:

def co = Bid.executeQuery(
   'select b.job from Bid b left join b.job j where j.dateCreated = ?',
   [fromDates[i])

Once you get this working you'll find that comparing dates like this rarely works because the dates have to agree to the millisecond, but that's a problem for another question :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top