表名作为HQL中的参数

时间:2013-09-02 15:46:24

标签: hibernate hql

假设我们有HQL查询:

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

但是,如果我想参数化表名怎么办?人们不能这样使用它:

String ageQuery = "select :table from people where name = :name";

Session session = getSession();
Query query = session.
        createSQLQuery(ageQuery).
        setParameter("table", "age").
        setParameter("name", "Thomas");

我已应用解决方法:

String ageQuery = "select :table: from people where name = :name";

Session session = getSession();
Query query = session.
        createSQLQuery(ageQuery.
        replace(":table:", "age")).
        setParameter("name", "Thomas");

......但我真的不喜欢它。还有其他解决方案吗?

2 个答案:

答案 0 :(得分:2)

您无法将表名定义为参数;你必须以旧的方式用字符串连接来构建语句 您的解决方法不是解决方法,而是继续进行的唯一方法 问题类似于Incorrect syntax near '@P0'. exception when create and drop Login in MSSQL

中描述的问题

答案 1 :(得分:1)

我在下面使用动态查询:

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();