Ascalonian
Ascalonian

Reputation: 15174

Get dynamic SQL column names from Hibernate

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.

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.

Using Hibernate, I create the query and get the data like so:

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"

So my question is: Is there a way through Hibernate to get these values dynamically?

Upvotes: 6

Views: 17411

Answers (4)

Xaltotun
Xaltotun

Reputation: 284

In 2018 I would suggest using NativeQueryTupleTransformer with native queries.

query.setResultTransformer(new NativeQueryTupleTransformer());

The result format is List<Tuple>. This format is very convenient to work with native SQL queries.

Upvotes: 1

user3487063
user3487063

Reputation: 3682

You can use :

q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();

to get column names in createSQLQuery.

For more details please refer to this question.

Upvotes: 14

Maarten Winkels
Maarten Winkels

Reputation: 2417

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.

Upvotes: 1

Anthony_Michael
Anthony_Michael

Reputation: 42

You can use the addScalar method to define the columns.

Look at 16.1.1 https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html

Upvotes: 1

Related Questions