Я могу установить переменные значения «где» restrictives:HQL: переменная колонка
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where test.col = :variableValue ");
criteria.setInteger("variableValue", 10);
Но можно установить переменные колонки, как это?
String variableColumn = "test.col1";
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where :variableColumn = :variableValue ");
criteria.setInteger("variableValue", 10);
criteria.setString("variableColumn", variableColumn);
Это результат:
Exception in thread "main" Hibernate: select .... where ?=? ...
org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
...
at _test.TestCriteria.main(TestCriteria.java:44)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value 'test.col1' to data type int.
...
UPDATE (рабочий раствор):
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where (:value1 is null OR test.col1 = :value1) AND
(:value2 is null OR test.col2 = :value2) "
Спасибо, но он говорит: 'Метод replace (String, String) не определен для типа Query'. Я случайно нашел еще один способ в документации - я обнов свой вопрос за несколько минут. – gaffcz
Как уже упоминалось в моем предлагаемом коде, 'query' - это строка, содержащая HQL. – nobeh
Omg, он работает и кажется более чистым, чем мое решение, еще раз спасибо! – gaffcz