3

Hibernate named parameters could not be inserted into SQL query:

String values="'a', 'b', 'c', 'd'";
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (:values)");
query.setParameter("values", values);
List<Object[]> data = query.list(); // returns data: size = 0 ...

However, if I will write:

String values="'a', 'b', 'c', 'd'";
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (" + values + ")");
List<Object[]> data = query.list(); // returns data: size = 15 ...

Second way returns me data instead of first way.

What I do wrong using named parameters in SQL?

2 Answers 2

10

The values variable should be a list or an array of Strings, not a string, as the parameter is in an 'IN' clause. So, change your code to the below and it should work:

String[] values= {"a", "b", "c", "d"};
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (:values)");
query.setParameterList("values", values);
List<Object[]> data = query.list();
Sign up to request clarification or add additional context in comments.

3 Comments

To be sure, I understand correectly that my concatenated string didn't work only because of IN clause, yep? If it will be something = "my_string" It will work, I quess?
@user1376885 Yes, it's a Hibernate's behaviour for IN clause. If it was a JPA Query, it should work with setParameter too.
If your query is something like select * from some_table where some_column = :value, then setParameter("value","my_string") will work. But, because the IN clause expects a list of values, it does not work when a string is passed.
2

Your second approach doesn't create a named parameter in the query, it just concatenates a string and you get a permanent query like it was made so:

SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN ('a', 'b', 'c', 'd')"); 

To make the first one work with Hibernate, you have to pass an array or a collection of Objects, not a single string and use a setParameterList method. Just like:

 query.setParameterList("reportID", new Object[]{"a","b","c","d"});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.