Let's assume we have the HQL query:
String ageQuery = "select age from people where name = :name";
Session session = getSession();
Query query = session.
createSQLQuery(nameQuery).
setParameter("name", "Thomas");
// query.list(); returns the result
But what if I want to parametrize the table name? One can't use it like this:
String ageQuery = "select :table from people where name = :name";
Session session = getSession();
Query query = session.
createSQLQuery(ageQuery).
setParameter("table", "age").
setParameter("name", "Thomas");
I've applied the workaround:
String ageQuery = "select :table: from people where name = :name";
Session session = getSession();
Query query = session.
createSQLQuery(ageQuery.
replace(":table:", "age")).
setParameter("name", "Thomas");
... but I don't really like it. Is there any other solution?
You can't define table name as parameter; you have to build statement with string concatenation in old fashion way.
Your workaround is not a workaround, but the only way to proceed.
Is an issue similar to the one described in Incorrect syntax near '@P0'. exception when create and drop Login in MSSQL
I use dynamic queries below: