java 从 Hibernate 获取动态 SQL 列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25125480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get dynamic SQL column names from Hibernate
提问by Ascalonian
I have an Oracle table that has a CLOB in it. Inside this CLOB can be a SQL statement. This can be changed at any time.
我有一个包含 CLOB 的 Oracle 表。在这个 CLOB 里面可以是一个 SQL 语句。这可以随时更改。
I am currently trying to dynamically run these SQL statements and return the column names and data back. This is to be used to dynamically create a table on the web page.
我目前正在尝试动态运行这些 SQL 语句并返回列名和数据。这将用于在网页上动态创建表格。
Using Hibernate, I create the query and get the data like so:
使用 Hibernate,我创建查询并获取数据,如下所示:
List<Object[]> queryResults = null;
SQLQuery q = session.createSQLQuery(sqlText);
queryResults = q.list();
This gets the data I need, but not the column names. I have tried using the getReturnAliases()
method, but it throws an error that the "java.lang.UnsupportedOperationException: SQL queries do not currently support returning aliases"
这将获得我需要的数据,但不是列名。我已尝试使用该getReturnAliases()
方法,但它引发了“java.lang.UnsupportedOperationException:SQL 查询当前不支持返回别名”的错误
So my question is: Is there a way through Hibernate to get these values dynamically?
所以我的问题是:有没有办法通过 Hibernate 动态获取这些值?
回答by user3487063
回答by Anthony_Michael
You can use the addScalar method to define the columns.
您可以使用 addScalar 方法来定义列。
Look at 16.1.1 https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
看 16.1.1 https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
回答by Maarten Winkels
You could implement a ResultTransformer ( http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/transform/ResultTransformer.html) and set it on the native query. I think with a native SQL query you get the aliases as specified in the SQL as alias parameter in the callback method.
您可以实现 ResultTransformer ( http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/transform/ResultTransformer.html) 并将其设置在本机查询上。我认为使用本机 SQL 查询,您可以获得 SQL 中指定的别名作为回调方法中的别名参数。
回答by Xaltotun
In 2018 I would suggest using NativeQueryTupleTransformer with native queries.
在 2018 年,我建议将 NativeQueryTupleTransformer 与本机查询一起使用。
query.setResultTransformer(new NativeQueryTupleTransformer());
The result format is List<Tuple>
. This format is very convenient to work with native SQL queries.
结果格式为List<Tuple>
. 这种格式对于使用本机 SQL 查询非常方便。