Reputation: 3201
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?
Upvotes: 1
Views: 6036
Reputation: 4182
I use dynamic queries below:
var query = session.CreateQuery(String.Format("update {0} set {1} = :updatevalue where {2} = :wherevalue",
MyClassMapping<UserEntity>.GetEntityName(),
MyClassMapping<UserEntity>.GetPropertyName(x => x.LastLoginTime),
MyClassMapping<UserEntity>.GetPropertyName(x => x.UserKey)))
.SetParameter("updatevalue", DateTime.Now)
.SetParameter("wherevalue", user.UserKey);
int rowsAffected = query.ExecuteUpdate();
Upvotes: 1
Reputation: 18383
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
Upvotes: 4