I am trying to figure out how to make this snip of code work:
def searchString = unchecked.join(",");
searchString = searchString.replace("\"", "'")
println("searchString: " + searchString);
def matches=Employee.executeQuery("select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name in (" +searchString + ")");
This is the query string passed to executeQuery
select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name in ('AA','BS')
which I can run in SQL Server and it returns the right results, however my grails code complains:
Stacktrace follows:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ON near line 1, column 59 [select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name in ('AA','BS')]
So what am I doing wrong? Is it the wrong domain object executing the query?
HQL is slightly/enough different than standard SQL. Assuming Hibernate knows about the relationship between these objects you can simplify your query to
It’s really important to use either named params or positional params with your query to prevent sql injection. Also if you really just want a list of employee id’s rather than instances you can put the
SELECT e.idback in there. There is also no reason to include the quotes since when the params are bound they will use the correct quotes for the database you are working with, given that the above code snippet also stripts out the quotes but you might rethink even letting them be included in the first place.