Search code examples
javahibernatenamed-query

Using a parameter to specify an expression in a named query


Can I use a query parameter to specify a table (object), column name, or expression in a named query?

For example, I would like to use a single query that allows me to switch between selecting the whole object or just the count.

select :param1
from TablePO t
where t.id = :param2

And setting the parameters in java like:

query.setParameter("param1", "t");
query.setParameter("param2", "2");

I want to avoid copy&paste by setting param1 like

query.setParameter("param1", "t");

or

query.setParameter("param1", "count(t)");

Solution

  • No, you can't. In the end, HQL parameters become JDBC prepared statement parameters, and you can't do that with prepared statements. Parameters hold values, and not arbitrary portions of a query. The database must be able to compute the query plan based on the parameterized query, and it would impossible if what you want to do was allowed.

    BTW, you would have found it youself if you had just tried it.