表名称作为HQL中的参数

表名称作为HQL中的参数

本文介绍了表名称作为HQL中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有HQL查询:

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



Session session = getSession();
查询查询=会话。
createSQLQuery(nameQuery)。
setParameter(name,Thomas);
// query.list();返回结果

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

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

Session session = getSession();
查询查询=会话。
createSQLQuery(ageQuery)。
setParameter(table,age)。
setParameter(name,Thomas);

我已经应用了解决方法:

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

Session session = getSession();
查询查询=会话。
createSQLQuery(ageQuery。
replace(:table:,age))。
setParameter(name,Thomas);

...但我不太喜欢它。有没有其他解决方案?

解决方案

您无法将表名称定义为参数;你必须以老式的方式建立以字符串连接的语句


你的解决方法不是解决方法,而是继续进行的唯一方法


是一个类似于描述在


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

这篇关于表名称作为HQL中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:10